[英]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.