React 路由器:在每个 <Link> 上执行自定义函数导航 [英] React router: execute custom function on every <Link> navigation

查看:30
本文介绍了React 路由器:在每个 <Link> 上执行自定义函数导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,如果已经回答了这个问题.但是有没有办法在每个 导航上执行自定义函数?最好不要创建自定义 包装器.

Sorry if this has been already answered. But is there a way to execute a custom function on every <Link> navigation? Preferably without creating a custom <Link> wrapper.

我想在我的应用程序中的每次导航之前将一些信息放入 sessionStorage.

I'd like to put some information to sessionStorage before every navigation inside my application.

谢谢

推荐答案

您可以使用 onClick 执行任何操作,例如

You can use onClick to perform any action, say

<Link
  to="/"
  onClick={() => console.log('Heading to /')} />

console.log 替换为一个可以执行 sessionStorage 更新等的函数,就是这样.

Replace console.log with a function that would perform sessionStorage update and such, and that's it.

另一种方法是使用 Route 组件的 onEnter 属性,在每次输入路径时执行某个函数:

Another way would be to use onEnter prop of Route component to execute a certain function per every route enter:

<Route
  path="/"
  component={App}
  onEnter={() => console.log('Entered /')} />

请参阅参考示例与 react-router 和react-redux.

这篇关于React 路由器:在每个 &lt;Link&gt; 上执行自定义函数导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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