React.js - componentWillReceiveProps被击中两次

问题描述:

我有一个像这样呈现的React.js组件:

I have a React.js component that's being rendered like so:

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

页面上有一些事件更新 this.state.email ,结果,通过渲染,它将一个新的电子邮件道具发送到社交组件。

There are some events on the page that update this.state.email, and as a result, go through render, which sends a new email prop to the Social component.

在这个社交组件中,我正在收听这样的更新:

In this Social component, I'm listening for updates like so:

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

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

That console line is being rendered twice which makes the UI flash twice along with calls to social networks.

我总是可以这样做:

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

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

But it felt a little hacky...

是否需要双重消息?如果是这样,好奇为什么?

Is the double message expected? and if so, curious why?

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

If not, what's the best way to both track down and eliminate it?

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

Your Social component is probably being rendered twice because setState is called twice on the parent component. It may be setting properties other than email but your render function is called so the Social component renders twice.

您可以在 Social 组件中实现 shouldComponentUpdate 方法以防止第二个渲染:

You can implement shouldComponentUpdate method in the Social component to prevent second rendering:

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