如何防止 useSearchBox() 在初始渲染时查询 Algolia 数据

问题描述 投票:0回答:1

如何防止 useSearchBox() 在初始渲染时查询 Algolia?

在用户在文本字段中输入字母之前,我不想查询数据。

谢谢!

javascript reactjs search text algolia
1个回答
0
投票

感谢 @cmgchess,我通过关注文档网站在 Algolia 文档中找到了答案。 https://www.algolia.com/doc/guides/building-search-ui/going-further/conditional-requests/react/

import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, SearchBox, Hits } from 'react-instantsearch';

const algoliaClient = algoliasearch(
  'YourApplicationID',
  'YourSearchOnlyAPIKey'
);

const searchClient = {
  ...algoliaClient,
  search(requests) {
    if (requests.every(({ params }) => !params.query)) {
      return Promise.resolve({
        results: requests.map(() => ({
          hits: [],
          nbHits: 0,
          nbPages: 0,
          page: 0,
          processingTimeMS: 0,
          hitsPerPage: 0,
          exhaustiveNbHits: false,
          query: '',
          params: '',
        })),
      });
    }

    return algoliaClient.search(requests);
  },
};

const App = () => (
  <InstantSearch searchClient={searchClient} indexName="instant_search">
    <SearchBox />
    <Hits />
  </InstantSearch>
);
© www.soinside.com 2019 - 2024. All rights reserved.