我有一个搜索组件,它对我的应用程序是全局的,并在顶部显示搜索结果。用户进行任何形式的导航(例如,单击搜索结果或使用浏览器上的“后退”按钮)后,我要重置搜索:清除结果和搜索输入字段。
目前,我正在使用Context
;进行处理。我有一个SearchContext.Provider
广播该resetSearch
函数的函数,无论我在哪里处理导航,我都有使用方resetSearch
在处理导航之前调用它(我使用useHistory
钩子以编程方式进行处理)。
对于浏览器控件上的后退按钮按下,这不起作用(因为这超出了我的控件范围)。
在Routes
渲染(或进行任何浏览器导航)之前,是否存在可以挂接的中间步骤,以确保resetSearch
调用了我的函数?
根据要求,下面是代码:
// App.js
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const resetSearch = () => {
setResults([]);
setQuery("");
};
<SearchContext.Provider value={{ resetSearch }}>
// all of my <Route /> components in this block
</SearchContext.Provider>
// BusRoute.js
const { resetSearch } = useContext(SearchContext);
const handleClick = stop => {
resetSearch();
history.push(`/stops/${stop}`);
};
return (
// some other JSX
<button onClick={() => handleClick(stop.code)}>{stop.name}</button>
);
您可以听history
更改:
useEffect(() => {
const unlisten = history.listen((location) => {
console.log('new location: ', location)
// do your magic things here
// reset the search: clear the results and the search input field
})
return function cleanup() {
unlisten()
}
}, [])
您可以在控制全局搜索值的父组件中使用此效果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句