[英]Elasticsearch search-ui with React
我有一個帶有旁邊和主要內容的 React 站點。 我想使用search-ui在網站上進行搜索。
搜索欄應該放在一邊,當用戶搜索某物時,結果應該顯示在主要內容上。 除了主要內容之外,還有兩個獨立的反應組件。
在我旁邊,我正在像這樣配置 search-ui SearchBox
<SearchBox
autocompleteResults={{
titleField: "title",
urlField: "url"
}}
autocompleteSuggestions={true}
onSubmit={searchTerm => {
navigate("/elastic-search?q=" + searchTerm);
}}
onSelectAutocomplete={(selection, {}, defaultOnSelectAutocomplete) => {
if (selection.suggestion) {
navigate("/elastic-search?q=" + selection.suggestion);
} else {
defaultOnSelectAutocomplete(selection);
}
}}
/>
因此,當用戶搜索某些內容時,應用程序將重定向到一個名為 elastic-search 的單獨頁面,我將通過導航方法在 URL 中傳遞 searchTerm。
在 MainContent 我有這樣的結果:
<Results titleField='title' urlField='url'/>
現在的問題是如何獲取 searchTerm 並在主要內容上顯示結果。 應用程序的結構是這樣的:
<App>
<SearchProvider config={config}>
<Aside /> ---- Here I have <SearchBox>
<MainContent /> ---- Here I have <Results>
</SearchProvider>
</App>
當我在 URL 中使用 searchTerm 搜索時,應用程序重定向到 /elastic-search,但結果未顯示。 如果我刷新頁面,它們就會顯示出來。 如何通知結果或重新呈現頁面,以便顯示搜索結果。
您的結果似乎缺少一些參數,應該看起來像這樣:
<>
<Results
titleField="title"
urlField=""
view={SearchView}
resultView={SearchResultView}
/>
</>
而您的SearchView (用於覆蓋此組件的默認視圖。)和SearchResultView (用於覆蓋單個結果視圖。)組件應該如下所示:
const SearchView = ({ children }) => {
return <div>{children}</div>
};
const SearchResultView = ({ result: searchResult }) => {
return <div>{searchResult.content}</div>
}
這是 Next.js 應用程序中的一個工作示例,其中包含import { useRouter } from "next/router";
需要用您的路由解決方案替換。 在搜索框組件中:
export const SearchBoxComponent = () => {
const router = useRouter();
return (
<>
<SearchBox
searchAsYouType={true}
autocompleteResults={{
titleField: "title",
urlField: "",
shouldTrackClickThrough: true,
clickThroughTags: ["test"],
}}
autocompleteSuggestions={true}
onSubmit={(searchTerm) => {
const urlEncodedQuery = encodeURI(searchTerm).replace(/%20/g, "+");
router.push(`/search?q=${urlEncodedQuery}`);
}}
...
</>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.