![](/img/trans.png)
[英]why `componentWillReceiveProps` is not necessary in React's “Lifting state up” example?
[英]State changed in componentWillReceiveProps is not showing up in the render
我在构造函数中定义了一个状态,就像这样
this.state={
datainaccordion:'',
};
现在在我的componentWillReceiveProps中,每次收到新的Props时,我都更改了状态,就像这样,
componentWillReceiveProps(nextProps){
console.log('something',nextProps);
if (nextProps.data) {
this.setState({ datainaccordion: nextProps.data });
}
console.log('this.state.datainaccordion ',this.state.datainaccordion);
}
我可以看到该控制台,并且每次收到新数据时它都可以正常工作,但是当我在渲染器中记录控制台的相同状态时,我看不到该控制台。 这可能是什么原因,为什么会发生呢? 另一件事是,我在渲染器中放置了另一个console.log('rendering'),甚至没有显示出来。 每当我获得新数据时,如何使它呈现? 我也在这里添加渲染部分。
render(){
console.log('rendering'); // this is not being printed
console.log('rung',this.state.datainaccordion);
// some logic to extract an array out of the data in this .state.datainaccordion and we call it arraytoloop
return (
<div>
<SomeComponentXYz
data={arraytoloop}
/>
</div>
); }
}
如@satyajeet jha所说
此组件是从PureComponent扩展的。 但是PureComponent已经实现了shouldComponentUpdate 。
React.PureComponent的shouldComponentUpdate()只会浅浅地比较对象。 ...
仅当您期望具有简单的道具和状态时才扩展PureComponent
我想您的字段datainaccordion是对象。 所以PureComponent中的shouldComponentUpdate将返回false并停止更新,因为它不检查新对象与旧对象之间的差异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.