router 生命周期中
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
每个钩子函数都只执行一次,如何在切换react-router的时候监听路由的变化,然后来执行指定的方法呢?
在react-router的API中看到 onUpdate(当 URL 改变时,需要更新路由的 state 时会被调用)但是具体怎么用呢,放在router的什么位置?
router 生命周期中
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
每个钩子函数都只执行一次,如何在切换react-router的时候监听路由的变化,然后来执行指定的方法呢?
在react-router的API中看到 onUpdate(当 URL 改变时,需要更新路由的 state 时会被调用)但是具体怎么用呢,放在router的什么位置?
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()
4 回答1.6k 阅读
2 回答1.1k 阅读✓ 已解决
2 回答2.6k 阅读
1 回答959 阅读✓ 已解决
1 回答686 阅读✓ 已解决
2 回答848 阅读✓ 已解决
2 回答1k 阅读
我们一般都会使用一个
state
管理器,比如react-redux,其中store
中有个subscriptions
就可以监听路由的变化。建议你使用封装过的react-redux之dvajs