Javascript React.js-组件将收到两次命中的道具
我有一个React.js组件,呈现如下:Javascript React.js-组件将收到两次命中的道具,javascript,reactjs,Javascript,Reactjs,我有一个React.js组件,呈现如下: <Social email={this.state.email} />; 控制台行被渲染两次,这使得UI在调用社交网络时闪烁两次 我总是可以做这样的事情: if (nextProps.email != this.props.email) { this.doSomeWork(); } 但是感觉有点不舒服 需要双重消息吗?如果是这样,为什么 如果没有,那么追踪和消除它的最佳方法是什么 您的Social组件可
<Social email={this.state.email} />;
控制台行被渲染两次,这使得UI在调用社交网络时闪烁两次
我总是可以做这样的事情:
if (nextProps.email != this.props.email) {
this.doSomeWork();
}
但是感觉有点不舒服
需要双重消息吗?如果是这样,为什么
如果没有,那么追踪和消除它的最佳方法是什么 您的
Social
组件可能被渲染两次,因为父组件上调用了两次setState
。它可能设置的属性不是电子邮件
,但是会调用渲染函数,因此社交
组件渲染两次
您可以在
Social
组件中实现shouldComponentUpdate
方法,以防止第二次渲染:
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.email != this.props.email;
}
双重渲染===双重调用,重新考虑渲染。:)<代码> SubDeCudioTebug 感觉就像一个创可贴,对吗?在<代码>组件中,我们将打印代码< >代码。第二次渲染时,它们是相同的。
componentWillReceiveProps
是否也应在状态更改时运行?否,您应使用componentWillUpdate
执行操作以响应状态更改。你可以在这里看到文档:好的,那么为什么我会看到更新通过componentWillReceiveProps
其中nextrops.email
和this.props.email
是一样的呢?使用shoulldcomponentupdate
是完全可取的,因为渲染比较时间变为常数。这就是像OM()这样的框架速度非常快的原因。如果您可以保证不可变性,只需在shouldComponentUpdate
函数中比较引用,那么您甚至可以跳过虚拟dom差异。可能正在阅读有关不可变性的内容,帮助程序可能会有所帮助:
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.email != this.props.email;
}