React router: execute custom function on every <Link> navigation

前端 未结 1 2089
一整个雨季
一整个雨季 2021-02-20 05:45

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

相关标签:
1条回答
  • 2021-02-20 06:11

    You can use onClick to perform any action, say

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

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


    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 /')} />
    

    See the reference, or example with react-router and react-redux.

    0 讨论(0)
提交回复
热议问题