我在构造函数中定义了一个状态,就像这样
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’s shouldComponentUpdate() only shallowly compares the objects. ...
Only extend PureComponent when you expect to have simple props and state
正如我所想,您的字段datainaccordion是对象。所以 PureComponent 中的 shouldComponentUpdate 将返回 false 并停止更新,因为它不检查新旧对象之间的差异
关于javascript - componentWillReceiveProps 中更改的状态未显示在渲染中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52071837/