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
React.js - componentWillReceiveProps being hit twice
提问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 email
prop to the Social
component.
页面上有一些事件是 update this.state.email
,结果是通过 render ,它会向组件发送一个新的email
prop Social
。
In this Social
component, 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 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
组件可能被渲染两次,因为setState
在父组件上被调用了两次。它可能正在设置属性,email
但您的渲染函数被调用以便Social
组件渲染两次。
You can implement shouldComponentUpdate
method in the Social
component to prevent second rendering:
您可以shouldComponentUpdate
在Social
组件中实现方法以防止二次渲染:
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.email != this.props.email;
}