【发布时间】:2026-02-09 19:30:01
【问题描述】:
我在构造函数中定义了一个状态,就像这样
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>
); }
}
【问题讨论】:
-
可以为 render() 添加代码吗?
-
你确定 shouldComponentUpdate 挂钩没有返回 false 吗?
-
渲染没问题。如上所述,可能错误在 shouldComponentUpdate 中,或者您从 PureComponent 扩展
-
嘿,我没有在任何地方使用过 ShouldComponentUpadte。
-
@KirillMatrosov 是的,我从 PureComponent 扩展而来。
标签: javascript reactjs