如何在 React 中使用 React Router 检测路由变化? [英] How to detect route changes using React Router in React?

查看:63
本文介绍了如何在 React 中使用 React Router 检测路由变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a search component that is global to my application, and displays search results right at the top. Once the user does any sort of navigation, e.g., clicking a search result or using the back button on the browser, I want to reset the search: clear the results and the search input field.

目前,我正在使用 Context 处理这个问题;我有一个 SearchContext.Provider 广播 resetSearch 函数,无论我在哪里处理导航,我都有消费者在处理导航之前调用 resetSearch (我使用 useHistory 钩子以编程方式完成.

Currently, I am handling this with a Context; I have a SearchContext.Provider that broadcasts the resetSearch function, and wherever I am handling navigation, I have consumers that invoke resetSearch before processing navigation (which I do programmatically with the useHistory hook).

这不适用于浏览器控件上的后退按钮按下(因为这是我无法控制的).

This doesn't work for back button presses on the browser's controls (since that is something out of my control).

在渲染我的 Routes(或发生任何浏览器导航)之前,是否有一个中间步骤可以让我挂钩,以确保调用我的 resetSearch 函数?

Is there an intermediate step before my Routes are rendered (or any browser navigation happens) that I can hook into, to make sure my resetSearch function is invoked?

根据要求,这里是代码:

As requested, here is the code:

// 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 变化:

You can listen to history changes:

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()
  }
}, [])

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

You can use this effect in your parent component which controls your global search's value.

这篇关于如何在 React 中使用 React Router 检测路由变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆