在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ react-router4 如何監(jiān)控路由跳轉(zhuǎn)事件,每次切換路由后都要執(zhí)行指定方法

react-router4 如何監(jiān)控路由跳轉(zhuǎn)事件,每次切換路由后都要執(zhí)行指定方法?

router 生命周期中
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
每個(gè)鉤子函數(shù)都只執(zhí)行一次,如何在切換react-router的時(shí)候監(jiān)聽(tīng)路由的變化,然后來(lái)執(zhí)行指定的方法呢?
在react-router的API中看到 onUpdate(當(dāng) URL 改變時(shí),需要更新路由的 state 時(shí)會(huì)被調(diào)用)但是具體怎么用呢,放在router的什么位置?

回答
編輯回答
心悲涼

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

直接使用history的方法history.listen()在切換路由的時(shí)候就會(huì)自動(dòng)觸發(fā)

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()
2017年4月13日 19:56
編輯回答
哚蕾咪

我們一般都會(huì)使用一個(gè)state管理器,比如react-redux,其中store中有個(gè)subscriptions就可以監(jiān)聽(tīng)路由的變化。
建議你使用封裝過(guò)的react-redux之dvajs

2018年7月23日 10:08
編輯回答
枕頭人

沒(méi)必要啊,直接用 componentDidUpdate 就可以吧。

2018年6月1日 15:29