k8w.io
使用React-Router后hash跳转会触发componentWillReceiveProps的坑
2017-11-29作者:k8w

通常对于componentWillReceiveProps,认为是外层Update时才会触发。
对于使用了React-Router的场景,通常也会理解为,当路由发生跳转时才会触发。
而实际上,当页面发生hash跳转(例如点击了<a href="#">XXX</a>)时,虽然路由没有跳转,但也会触发componentWillReceiveProps

场景

  1. 使用了componentWillReceiveProps
  2. 在点击诸如<a href='#xxx'>XXX</a>时会触发componentWillReceiveProps
  3. 实际不希望此时触发

原因

React的componentWillReceiveProps触发实际受2个条件制约:

  1. Component.props更新
  2. Component.context更新

而每次URL的pathname变化或hash变化,React-Router都会触发context里的router变化。

从而会触发componentWillReceiveProps

解决方案

为避免受上述原因影响,建议在componentWillReceiveProps检查props是否发生变化。

componentWillReceiveProps(nextProps, nextContext){
    if(nextProps !== this.props){
        //path变化会执行这里
        //仅hash变化不会执行这里
    }
}
(正文完)
留言(0条)
发表新留言
您的大名:
必填
电子邮箱:
不公开,仅用于向你发送回复
粤ICP备17160324号-3