react-router4 如何监控路由跳转事件,每次切换路由后都要执行指定方法?

router 生命周期中
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
每个钩子函数都只执行一次,如何在切换react-router的时候监听路由的变化,然后来执行指定的方法呢?
在react-router的API中看到 onUpdate(当 URL 改变时,需要更新路由的 state 时会被调用)但是具体怎么用呢,放在router的什么位置?

阅读 15.9k
3 个回答

我们一般都会使用一个state管理器,比如react-redux,其中store中有个subscriptions就可以监听路由的变化。
建议你使用封装过的react-redux之dvajs

https://github.com/ReactTrain...

直接使用history的方法history.listen()在切换路由的时候就会自动触发

import createHistory from "history/createBrowserHistory"

const history = createHistory()

// Get the current location.
const location = history.location

// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.pathname, location.state)
})

// Use push, replace, and go to navigate around.
history.push("/home", { some: "state" })

// To stop listening, call the function returned from listen().
unlisten()

没必要啊,直接用 componentDidUpdate 就可以吧。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题