繁体   English   中英

React.js - componentWillReceiveProps被击中两次

[英]React.js - componentWillReceiveProps being hit twice

我有一个React.js组件,它被渲染如下:

    <Social email={this.state.email} />;

页面上有一些事件更新this.state.email ,因此,通过render,它会向Social组件发送一个新的email道具。

在这个Social组件中,我正在倾听这样的更新:

  componentWillReceiveProps: function(nextProps) {
    console.log('received props update', nextProps.email);
    this.doSomeWork();
  }

该控制台线被渲染两次,这使得UI闪烁两次以及对社交网络的调用。

我总是可以这样做:

    if (nextProps.email != this.props.email) {
      this.doSomeWork();
    }

但它感觉有点hacky ......

这是双重信息吗? 如果是这样,好奇为什么?

如果不是,那么追踪和消除它的最佳方法是什么?

您的Social组件可能会被渲染两次,因为在父组件上调用了setState两次。 它可能是设置除email之外的属性,但您的渲染函数被调用,因此Social组件呈现两次。

您可以在Social组件中实现shouldComponentUpdate方法以防止第二次呈现:

shouldComponentUpdate: function(nextProps, nextState) {
    return nextProps.email != this.props.email;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM