【发布时间】:2020-09-29 11:37:37
【问题描述】:
我正在尝试在反应钩子中实现 algolia。我已经创建了索引并分配了可搜索的属性。
我的可搜索属性是 index.customerFirstName 和 index.customerLastName。我没有设置自定义搜索排名。
索引记录如下所示:
{
"indexData": {
"customerFirstName": "Ivor",
"customerLastName": "Cutler"
},
"objectID": "xxxxxxxxxxxxxxxxxxxxxx"
}
使用 useState 我初始化变量:
const [ searchClient, setSearchClient ] = useState(null);
const [ search, setSearch ] = useState('');
const [ searchIndex, setSearchIndex ] = useState();
我的 useEffect 等待登录 firebase 以获取记录,然后将搜索客户端设置为访问 algolia 索引。如果成功,它应该填充变量 searchClient,这似乎有效,因为当 useEffect 检测到更改时,它会记录 searchClient。
useEffect (() => {
firebase.auth().onAuthStateChanged((user) => {
if (user && !searchClient) {
setSearchClient(
algoliasearch(
process.env.REACT_APP_ALGOLIA_APP_ID,
process.env.REACT_APP_ALGOLIA_SEARCH_KEY
)
)
}
});
if (searchClient !== null && !searchIndex) {
setSearchIndex(
searchClient.initIndex('Sessions')
);
console.log("SEARCH CLIENT", searchClient)
}
if (searchIndex && search) {
console.log('SEARCH INDEX: ', searchIndex, search);
getHits();
}
}, [search, searchClient, searchIndex, sessions, sessionData, showSessionData])
当搜索(查询)的值发生变化时调用 gethits() 函数:
const getHits = () => {
searchIndex.search(
search
).then(console.log)
}
然而我的 hits 数组总是空的。我的索引中有正确字段的数据?什么给了?
因为搜索查询出现在命中 JSON 中,所以它正在搜索某些内容?
【问题讨论】:
标签: reactjs react-hooks algolia