1

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

提前致谢。

4

1 回答 1

5

我个人没有在 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;

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

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;

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

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;

完整示例可在此处获得。

于 2021-07-27T18:13:03.603 回答