我如何 运行 使用 react-router 5 从某些页面更改路由代码

How can I run code on a route change from certain pages using react-router 5

我在 v4 上找到了很多使用 onLeave 函数的例子。然而,这似乎在 v4 之后停产了。

我看过一些 <Prompt> 示例,但我认为这不是我要找的。如果你有合适的案例,我愿意接受。

我的场景: React v16 应用程序,其中我有多个 tables。我在商店(全局状态)中有一个部分,我保留某些 ui 偏好。 table 分页并重用一些相同的状态信息进行分页、排序等

用户故事 - 用户选择第 4 页,然后导航到另一个 table,仍在第 4 页(从商店读取分页)。我只是想从状态中清除值(我使用的是 redux,所以我将调用一个操作来执行此操作)但是我如何触发它,例如,仅在我的应用程序中的几条路线上。这样我就可以在休假时重置它,并在用户到达下一个 table?

时准备就绪
//edit for comment 1, basic example
const routes = [
  {
    path: "/one-thing",
    component: OneThing,
  },
  {
    path: "/two-thing",
    component: TwoThing,
  }, 
...

这是一个巨大的应用程序,但这可能会澄清。当我离开路径 /one-thing 时,我如何 运行 编码?

我们以前可以在 v4 中做到这一点

  {
    path: "/two-thing",
    component: TwoThing,
    onLeave: doAThing,
  }, 

听起来您可以通过父组件中的 history 对象监听当前位置的变化。

history.listen

import { useHistory } from 'react-router-dom';
import { useEffect } from "react";

...

const history = useHistory();

useEffect(() => {
  const unlisten = history.listen((location, action) => {
    console.log('Route changed', { location, action });
    // Apply route change logic, i.e. dispatch to store
  });
  return unlisten;
}, []);

或者在table组件中使用卸载useEffect清理功能。

import { useEffect } from "react";

...

useEffect(() => {
  return() => {
    // component unmounting (maybe from route change)
    // Apply route change logic, i.e. dispatch to store
  };
}, []);