1、原生js硬剛
componentDidMount(){
window.addEventListener('hashchange', this.routerEvent); } componentWillUnmount(){ window.removeEventListener('hashchange',this.routerEvent); } routerEvent = (e)=>{ // e.target.location.hash.replace("#","") // 去掉#就能獲取即將跳轉的那個路由的url了 }
Tips:addEventListener之后一定要remove,否則跳轉路由后,原有的事件又沒消除,
會導致注冊了越來越多的事件;
另外,removeEventListener的第二個參數指向的函數 必須要跟addEventListener傳入的函數是同一個函數(這點非常容易錯)
這種方式還有種缺點,它只監聽到了hash的變化,
而如果是#aaa?page=1跳到了#aaa?page=2,監聽不到;
vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com
2、react router自帶的history.listen
componentDidMount(){
this.props.history.listen(route => { console.log(route); // 這個route里面有當前路由的各個參數信息 }); }
但是,發現,這個history.listen,在組件銷毀的時候並不會銷毀,事件仍然存在。
如果多次進入同一個路由,這個componentDidMount重復觸發,listen重復綁定,跟addEventListener差不多了,
而也沒有找到removeEventListener方法。。。
打印一下this.props.history
console.log(this.props.history)
我們可以看到,有listen方法,但是卻沒有找到解綁的方法;
通過百度沒有找到方法,文檔里面也沒寫怎么解綁,
一籌莫展之際,那只能用最后一個方法:翻源碼。
說干就干,找到了/react-router/cjs/react-router.js
到這里我們可以推測,
this.props.history.listen()這個函數執行之后,返回值為一個unlisten函數,
unlisten就是listen的解綁函數!
於是代碼變成了這樣
let UNLISTEN; class Client extends React.Component { ..., componentDidMount(){ // UNLISTEN變量用來接收解綁函數 UNLISTEN = this.props.history.listen(route => { console.log(route); }); } componentWillUnmount(){ UNLISTEN && UNLISTEN(); // 執行解綁 } }