【发布时间】:2019-04-05 01:21:37
【问题描述】:
我目前在我的应用程序中使用 PureComponent 父组件和子组件。我希望 PureComponent 仅在状态或道具更改时才更新。为了确保这一点,每次调用它的 componentDidUpdate() 方法时,我都有一个子组件记录一些内容。该应用程序如下所示:
class Parent extends React.PureComponent{
constructor(props){
super(props);
this.state = {
item1: null,
item2: null,
list1: [],
list2: [],
}
render(){
let combinedList= [...this.state.list1, ...this.state.list2];
return(
<React.Fragment>
<Child myList={combinedList} />
<OtherChild item={this.state.item1} />
</React.Fragment>
);
子组件看起来像这样:
class Child extends React.PureComponent{
constructor(props){
super(props);
}
componentDidUpdate(){
console.log("Child updated");
}
render(){
return(
....
);
}
例如,当 Parent 组件中 item2 的状态发生变化时,Child 组件会记录“Child updated”。我有点困惑,因为子组件没有接收 item1 作为道具,并且它的状态没有改变。发生这种情况是因为父组件重新渲染了它的所有子组件吗?或者可能是因为 Child 对其myList 道具所做的浅比较表明它已经改变了?除了编写我自己的 shouldComponentUpdate() 方法之外,如何防止 Child 在每次 Parent 重新渲染时重新渲染?
【问题讨论】:
标签: javascript reactjs