您好,欢迎访问一九零五行业门户网

分析:React-Router路由跳转时触发两次render的情况

问题: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 点击link3         return this.props.location.action === pop4 }
备注:facebook官方说此情况是 react-router 的bug,已经在 ^4.x.x中修复了。
  以上内容均是本人在实际项目开发中所遇所得,每个人所遇bug不同,请大神轻喷。谢谢! 
以上就是分析:react-router路由跳转时触发两次render的情况的详细内容。
其它类似信息

推荐信息