添加CustomSearchBox时出现this.props.contextValue.store.getState不是函数错误
问题:添加自定义搜索框后触发“this.props.contextValue.store.getState is not a function”错误
我按照Autocomplete文档添加自定义输入组件后遇到问题,添加CustomSearchBox组件时触发错误:this.props.contextValue.store.getState is not a function,请问哪里操作有误?
主组件代码:
<InstantSearch searchClient={algoliaClient} indexName="plp" > <CustomSearchBox /> // 添加此组件时触发错误 <Autocomplete searchClient={algoliaClient} placeholder="Search products" detachedMediaQuery="none" openOnFocus /> <RefinementList attribute="DIAMETER" /> <HitWrapper> <Hits hitComponent={Hit} /> </HitWrapper> </InstantSearch>
自定义搜索框组件代码:
import React from 'react'; import { connectSearchBox } from 'react-instantsearch-dom'; const SearchBox = ({ currentRefinement, isSearchStalled, refine }) => ( <form noValidate action="" role="search"> <input type="search" value={currentRefinement} onChange={event => refine(event.currentTarget.value)} /> {isSearchStalled ? 'My search is stalled' : ''} </form> ); const CustomSearchBox = connectSearchBox(SearchBox); export default CustomSearchBox;
原因及解决方案
错误核心是混合使用了两个不兼容的Algolia组件体系:
react-instantsearch-dom(用于connectSearchBox)是旧版InstantSearch的DOM绑定库<Autocomplete>属于新版@algolia/autocomplete-react组件,它和旧版的上下文体系不兼容
解决步骤:
- 统一组件体系:用新版Autocomplete的API实现自定义搜索框,替代旧版的
connectSearchBox。 - 重写自定义搜索框:
import React from 'react'; import { useAutocomplete } from '@algolia/autocomplete-react'; const CustomSearchBox = ({ inputRef, ...props }) => { const { query, setQuery, isSearchStalled } = useAutocomplete(); return ( <form noValidate action="" role="search"> <input ref={inputRef} type="search" value={query} onChange={(event) => setQuery(event.currentTarget.value)} {...props} /> {isSearchStalled ? '搜索请求延迟中' : ''} </form> ); }; export default CustomSearchBox; - 调整组件嵌套结构:把自定义搜索框通过
<Autocomplete>的renderInput属性传入,而不是直接放在<InstantSearch>下:<InstantSearch searchClient={algoliaClient} indexName="plp" > <Autocomplete searchClient={algoliaClient} placeholder="Search products" detachedMediaQuery="none" openOnFocus renderInput={({ ref, ...props }) => ( <CustomSearchBox inputRef={ref} {...props} /> )} /> <RefinementList attribute="DIAMETER" /> <HitWrapper> <Hits hitComponent={Hit} /> </HitWrapper> </InstantSearch>
备选方案:
如果一定要用旧版connectSearchBox,则需要移除<Autocomplete>组件,改用旧版的<SearchBox>组件体系,保证所有组件都来自react-instantsearch-dom。
内容的提问来源于stack exchange,提问作者mark
相关产品推荐
相关产品推荐

