React.js - componentWillReceiveProps被击中两次

bra*_*ert 12 javascript reactjs

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

    <Social email={this.state.email} />;
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

我总是可以这样做:

    if (nextProps.email != this.props.email) {
      this.doSomeWork();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

nil*_*gun 17

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

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

shouldComponentUpdate: function(nextProps, nextState) {
    return nextProps.email != this.props.email;
}
Run Code Online (Sandbox Code Playgroud)

  • `shouldComponentUpdate`感觉像是一个创可贴,对吧? (2认同)