React Router Link 回调函数

3

我正在使用react-router-dom v4,想在点击链接导航/路由变更后执行回调函数。

<nav>
  <ul>
    {this.routes.map((route) => <li key={route.id}><Link to={route.path} >{route.title}</Link></li>)}
  </ul>
</nav>

<main>
  {this.routes.map((route) => 
    <Route 
      key={route.id}
      path={route.path}
      onEnter={() = > console.log('callback after route change')}
      exact
      component={route.component} />
   )}
</main>

我尝试在Route上使用onEnter,但它不起作用。

1个回答

0

在 react-router v4 中,onEnter 已被移除,但在 react-router v3 中仍可使用。

你可以尝试使用要导航到的组件的 componentWillMount 函数。

希望能帮到你。


谢谢回复,但那种解决方案意味着要为每个组件编写componentWillMount函数。 - que1326
1
你可以创建一个高阶组件,在每个路由上调用它,并在高阶组件内部添加算法,这样就可以避免多次编写相同的代码。 - Piyush Zalani
1
componentWillMount已被弃用 https://reactjs.org/docs/react-component.html#unsafe_componentwillmount - UjinT34

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接