如何在React中使用React Router检测路由变化?

Fam*_*Fam 4 reactjs react-router react-router-dom

我有一个对我的应用程序来说是全局的搜索组件,并在顶部显示搜索结果。一旦用户进行任何类型的导航,例如单击搜索结果或使用浏览器上的后退按钮,我想重置搜索:清除结果和搜索输入字段

目前,我正在用 ; 处理这个问题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>
Run Code Online (Sandbox Code Playgroud)
// 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>
);
Run Code Online (Sandbox Code Playgroud)

Aje*_*hah 5

你可以听听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()
  }
}, [])
Run Code Online (Sandbox Code Playgroud)

您可以在控制全局搜索值的父组件中使用此效果。