在过去的两周里,我一直在努力让 Algolia 的 react 即时搜索为我正在构建的 Next.js 网络应用程序完全实施。
我阅读了文档,并能够为搜索框和点击创建和使用自定义小部件。我能够使用规则设置 URL 路由。我需要知道的是如何让搜索框连接到单独的结果页面,以及如何让我的“点击”在点击时重定向到他们的页面。基本上,我正在尝试构建一些你会在 Netflix、Twitch 或 Youtube 上看到的东西。我可以在搜索栏中输入某些内容并将其发送到结果页面,然后我可以从那里单击产品或“点击”,这会将我重定向到它需要去的地方。
这是我的代码:
import React from 'react';
import { useRef, useState, useEffect } from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch } from 'react-instantsearch-dom';
import { Index } from 'react-instantsearch-dom';
import { Configure } from 'react-instantsearch-dom';
import { Pagination } from 'react-instantsearch-dom';
const searchClient = algoliasearch(
'XXXXXXXXXX',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);
const Hit = ({ hit }) => <p>{hit.title}</p>;
import { connectSearchBox } from 'react-instantsearch-dom';
const SearchBox = ({ currentRefinement, isSearchStalled, refine }) => (
<form noValidate action="" role="search">
<div className="container flex justify-center items-center px-4 sm:px-6 lg:px-8 relative">
<input
type="search"
placeholder='Search Documentation'
value={currentRefinement}
onChange={event => refine(event.currentTarget.value)}
className="h-7 w-96 pr-8 pl-5 rounded z-0 hover:text-gray-500 outline-none border-b-2"
/>
<i className="fa fa-search text-gray-400 z-20 hover:text-gray-500"></i>
</div>
<button onClick={() => refine('')}>Reset query</button>
{isSearchStalled ? 'My search is stalled' : ''}
</form>
);
const CustomSearchBox = connectSearchBox(SearchBox);
import { connectHits } from 'react-instantsearch-dom';
const Hits = ({ hits }) => (
<table className="table-auto">
{hits.map(hit => (
<tbody>
<tr>
<td className="text-black font-bold" key={hit.objectID}>{hit.title}</td>
</tr>
</tbody>
))}
</table>
);
const CustomHits = connectHits(Hits);
import { QueryRuleCustomData } from 'react-instantsearch-dom';
function SearchApp({location, history}) {
const [showHits, setShowHits] = useState(false);
return (
<div>
<>
<InstantSearch
indexName="prod_Directory"
searchClient={searchClient}
>
<Index indexName="prod_Directory">
{/* Widgets */}
<div>
<CustomSearchBox onFocus={()=>setShowHits(true)} onBlur={()=>setShowHits(false)}/>
{showHits ? <CustomHits className="table-auto"/> : null}
</div>
</Index>
<Configure
hitsPerPage={2}
/>
<QueryRuleCustomData
transformItems={items => {
const match = items.find(data => Boolean(data.redirect));
if (match && match.redirect) {
window.location.href = match.redirect;
}
return [];
}}
>
{() => null}
</QueryRuleCustomData>
</InstantSearch>
</>
</div>
)
}
export default SearchApp
Algolia 这里也有例子:
https://www.algolia.com/doc/guides/building-search-ui/resources/demos/react/