javascript React.js - componentWillReceiveProps 被击中两次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27628504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:44:14  来源:igfitidea点击:

React.js - componentWillReceiveProps being hit twice

javascriptreactjs

提问by brandonhilkert

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

我有一个 React.js 组件,它的呈现方式如下:

    <Social 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 emailprop to the Socialcomponent.

页面上有一些事件是 update this.state.email,结果是通过 render ,它会向组件发送一个新的emailprop Social

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

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

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

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

该控制台行被渲染两次,这使得 UI 随着对社交网络的调用而闪烁两次。

I could always do something like:

我总是可以做这样的事情:

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

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?

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

回答by nilgun

Your Socialcomponent is probably being rendered twice because setStateis called twice on the parent component. It may be setting properties other than emailbut your render function is called so the Socialcomponent renders twice.

您的Social组件可能被渲染两次,因为setState在父组件上被调用了两次。它可能正在设置属性,email但您的渲染函数被调用以便Social组件渲染两次。

You can implement shouldComponentUpdatemethod in the Socialcomponent to prevent second rendering:

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

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