react-router: how to get the previous route in onEnter handler?

廉价感情. 提交于 2019-12-02 02:24:42
mirza.adipradhana

Are you trying to get the previous path when the user navigate to new path through address bar or using react-router like this.context.router.push()?

If the navigation is using react-router, maybe these simple way would get what you're looking for:

1. Pass prevPath using query-params

Navigation might look like this:

`<Link to="/next" query={{ prevPath: this.props.location.pathname }}> Your Next path</Link>`

Now, you can get your prevPath value on onEnterHandler method by using this: nextState.location.query.prevPath

  • Cons: the query will appear on address bar.
  • Pros: you are still able to get your prevPath when user is navigating through address bar (direct path access).

2. Pass prevPath using state

Navigation might look like this:

`<Link to="/next" state={{ prevPath: this.props.location.pathname }}> Your Next path</Link>`

Now, you can get your prevPath value on onEnterHandler method by using this: nextState.location.state.prevPath

  • Cons: the query won't appear on address bar.
  • Pros: you are not able to get your prevPath when user is navigating through address bar (direct path access).

In addition, the cons of those method is you should assign a prevPath value into each of Link components. Create a wrapper component for the Link component would solve this issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!