gpt4 book ai didi

reactjs - 如何实现rtk的createApi查询去抖动

转载 作者:行者123 更新时间:2023-12-05 00:44:04 27 4
gpt4 key购买 nike

有人可以帮助我使用 creatApi 和 redux 工具包中的查询实现来实现去抖动功能。

提前致谢。

最佳答案

我个人没有在 RTK Query 中找到任何开箱即用的去抖动实现。但是你可以自己实现。

定义一个 API。我正在使用一个开放图书馆的:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

type BooksSearchResult = {
docs: Book[];
};

type Book = {
key: string;
title: string;
author_name: string;
first_publish_year: number;
};

export const booksApi = createApi({
reducerPath: 'booksApi',
baseQuery: fetchBaseQuery({ baseUrl: 'http://openlibrary.org/' }),
endpoints: builder => ({
searchBooks: builder.query<BooksSearchResult, string>({
query: term => `search.json?q=${encodeURIComponent(term)}`,
}),
}),
});

export const { useSearchBooksQuery } = booksApi;

接下来你需要的是 debounce hook,它保证某些值只有在指定的延迟后才会改变:

function useDebounce(value: string, delay: number): string {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}

在您的搜索表单上使用 debounce hook:

import React, { useEffect, useState } from "react";
import BookSearchResults from "./BookSearchResults";

function useDebounce(value: string, delay: number): string {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(handler);
};
}, [value, delay]);

return debouncedValue;
}

const DebounceExample: React.FC = () => {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearchTerm = useDebounce(searchTerm, 500);

return (
<React.Fragment>
<h1>Debounce example</h1>
<p>Start typing some book name. Search starts at length 5</p>
<input
className="search-input"
type="text"
placeholder="Search books"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<BookSearchResults searchTerm={debouncedSearchTerm}></BookSearchResults>
</React.Fragment>
);
};

export default DebounceExample;

在搜索结果组件中使用搜索查询 Hook 。它对搜索词值使用自己的状态,如果您想为去抖动值添加额外的“过滤器”,这非常方便(例如,仅当搜索词的长度大于某个值时才开始查询)。

import React, { useState, useEffect } from "react";
import { useSearchBooksQuery } from "./booksApi";

type BookSearchResultsProps = {
searchTerm: string;
};

const BookSearchResults: React.FC<BookSearchResultsProps> = ({
searchTerm
}: BookSearchResultsProps) => {
const [filteredSearchTerm, setFilteredSearchTerm] = useState(searchTerm);
const { data, error, isLoading, isFetching } = useSearchBooksQuery(
filteredSearchTerm
);
const books = data?.docs ?? [];

useEffect(() => {
if (searchTerm.length === 0 || searchTerm.length > 4) {
setFilteredSearchTerm(searchTerm);
}
}, [searchTerm]);

if (error) {
return <div className="text-hint">Error while fetching books</div>;
}

if (isLoading) {
return <div className="text-hint">Loading books...</div>;
}

if (isFetching) {
return <div className="text-hint">Fetching books...</div>;
}

if (books.length === 0) {
return <div className="text-hint">No books found</div>;
}

return (
<ul>
{books.map(({ key, title, author_name, first_publish_year }) => (
<li key={key}>
{author_name}: {title}, {first_publish_year}
</li>
))}
</ul>
);
};

export default BookSearchResults;

完整示例可用here .

关于reactjs - 如何实现rtk的createApi查询去抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68330104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com