問題:React-Router路由跳轉時,render觸發兩次,導致頁面重復渲染。
原因:項目中使用的react-router ^3.x.x。react-router路由跳轉時,this.props.location.action的值會有兩種狀態。這兩種狀態都會觸發render。故頁面渲染兩次。
1、當點擊Link時,this.props.location.action=PUSH,2、當瀏覽器前進后退時,this.props.location.action=POP。
所以當點擊了Link時,狀態先是PUSH,之后瀏覽器發生前進后退,狀態變為POP。
解決方案:在路由層,使用react周期函數 shouldComponentUpdate(生命周期不熟悉的同學請另查資料) 進行 this.props.location.action值得判斷。根據項目實際需要判斷值是PUSH,或者是POP。
本人選擇的是POP,因為項目中有些需求要使用到 window.location.hash='xxxxxxxx',這種情況PUSH是觸發不到的,所以路由跳轉會失敗。
1 shouldComponentUpdate() { 2 // POP 瀏覽器前進后退, PUSH 點擊Link 3 return this.props.location.action === "POP" 4 }
備注:facebook官方說此情況是 react-router 的BUG,已經在 ^4.x.x中修復了。
以上內容均是本人在實際項目開發中所遇所得,每個人所遇BUG不同,請大神輕噴。謝謝!
