ReactiveSearch中如何在结果页实现功能正常的搜索导航标签
问题根因
你当前ResultsViewPage组件中state的selected字段未正确赋值,导致生成链接时查询参数为空。之前在DataSearch同文件下可以正常工作,是因为可以直接拿到DataSearch组件的实时输入/提交值,拆分到结果页后没有同步获取查询词的逻辑。
实现方案
方案1:从当前页面URL解析查询词(推荐,无需依赖ReactiveSearch内部状态)
直接从结果页的URL参数中提取q值,不需要跨组件传递状态,兼容性最好。
首先在ResultsViewPage中添加解析URL参数的逻辑:
// ResultsViewPage组件内添加解析查询参数的方法 getQueryParam = (name: string) => { const urlParams = new URLSearchParams(this.props.location.search); return urlParams.get(name) || ''; } render() { // 替换原来从state取selected的逻辑,直接从URL取q参数 const query = this.getQueryParam('q'); // ...其余省略代码 <ResultNavigationTabs2 className={classes.myNavigationTabs} items={[ { text: "Web", link: `/search?q="${query}"` }, { text: "News", link: `/news?q="${query}"` }, { text: "Shopping", link: `/shopping?q="${query}"` }, ]} /> }
如果你的ResultsViewPage没有被withRouter包裹,记得导出的时候加上withRouter(ResultsViewPage)。
方案2:通过ReactiveSearch的ComponentContext共享查询状态
如果你需要用ReactiveSearch的全局状态管理,可以用withComponentContext高阶组件直接获取DataSearch组件的值,无需手动传参:
- 先给你的DataSearch组件设置
componentId属性,比如:
<DataSearch componentId="mainSearch" // 其余原有配置保持不变 />
- 在ResultsViewPage中用withComponentContext获取查询值:
import { withComponentContext } from '@appbaseio/reactivesearch'; class ResultsViewPage extends Component { render() { // 从props中取mainSearch对应的查询值 const selected = this.props.mainSearch?.value || ''; // 其余原有渲染逻辑保持不变 } } // 导出的时候指定要监听的componentId export default withComponentContext(['mainSearch'])(ResultsViewPage);
以上两种方案任选其一即可修复链接查询参数为空的问题。
内容的提问来源于stack exchange,提问作者user3125823
相关产品推荐
相关产品推荐

