React.js - componentWillReceiveProps被击中两次 [英] React.js - componentWillReceiveProps being hit twice

查看:108
本文介绍了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?

推荐答案

您的社交组件可能会被渲染两次,因为<$ c在父组件上调用$ c> 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;
}

这篇关于React.js - componentWillReceiveProps被击中两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆