分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況
來源:懂視網(wǎng)
責(zé)編:小采
時間:2020-11-27 20:16:14
分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況
分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況:問題:React-Router路由跳轉(zhuǎn)時,render觸發(fā)兩次,導(dǎo)致頁面重復(fù)渲染。原因:項目中使用的react-router ^3.x.x。react-router路由跳轉(zhuǎn)時,this.props.location.action的值會有兩種狀態(tài)。這兩種狀態(tài)都會觸發(fā)render。故頁面渲染兩次。 1、當點擊Link
導(dǎo)讀分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況:問題:React-Router路由跳轉(zhuǎn)時,render觸發(fā)兩次,導(dǎo)致頁面重復(fù)渲染。原因:項目中使用的react-router ^3.x.x。react-router路由跳轉(zhuǎn)時,this.props.location.action的值會有兩種狀態(tài)。這兩種狀態(tài)都會觸發(fā)render。故頁面渲染兩次。 1、當點擊Link

問題:React-Router路由跳轉(zhuǎn)時,render觸發(fā)兩次,導(dǎo)致頁面重復(fù)渲染。
原因:項目中使用的react-router ^3.x.x。react-router路由跳轉(zhuǎn)時,this.props.location.action的值會有兩種狀態(tài)。這兩種狀態(tài)都會觸發(fā)render。故頁面渲染兩次。
1、當點擊Link時,this.props.location.action=PUSH,2、當瀏覽器前進后退時,this.props.location.action=POP。
所以當點擊了Link時,狀態(tài)先是PUSH,之后瀏覽器發(fā)生前進后退,狀態(tài)變?yōu)镻OP。
解決方案:在路由層,使用react周期函數(shù) shouldComponentUpdate(生命周期不熟悉的同學(xué)請另查資料) 進行 this.props.location.action值得判斷。根據(jù)項目實際需要判斷值是PUSH,或者是POP。
本人選擇的是POP,因為項目中有些需求要使用到 window.location.hash='xxxxxxxx',這種情況PUSH是觸發(fā)不到的,所以路由跳轉(zhuǎn)會失敗。
1 shouldComponentUpdate() {2 // POP 瀏覽器前進后退, PUSH 點擊Link3 return this.props.location.action === "POP"4 }
備注:facebook官方說此情況是 react-router 的BUG,已經(jīng)在 ^4.x.x中修復(fù)了。
以上內(nèi)容均是本人在實際項目開發(fā)中所遇所得,每個人所遇BUG不同,請大神輕噴。謝謝!
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況
分析:React-Router路由跳轉(zhuǎn)時觸發(fā)兩次render的情況:問題:React-Router路由跳轉(zhuǎn)時,render觸發(fā)兩次,導(dǎo)致頁面重復(fù)渲染。原因:項目中使用的react-router ^3.x.x。react-router路由跳轉(zhuǎn)時,this.props.location.action的值會有兩種狀態(tài)。這兩種狀態(tài)都會觸發(fā)render。故頁面渲染兩次。 1、當點擊Link