问题:React-Router路由跳转时,render触发两次,致使页面重复渲染。react
缘由:项目中使用的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。react-router
因此当点击了Link时,状态先是PUSH,以后浏览器发生前进后退,状态变为POP。函数
解决方案:在路由层,使用react周期函数 shouldComponentUpdate(生命周期不熟悉的同窗请另查资料) 进行 this.props.location.action值得判断。根据项目实际须要判断值是PUSH,或者是POP。
this
本人选择的是POP,由于项目中有些需求要使用到 window.location.hash='xxxxxxxx',这种状况PUSH是触发不到的,因此路由跳转会失败。code
shouldComponentUpdate() { // POP 浏览器前进后退, PUSH 点击Link return this.props.location.action === "POP" }
备注:facebook官方说此状况是 react-router 的BUG,已经在 ^4.x.x中修复了。router