gpt4 book ai didi

javascript - React PureComponent 在不应该更新的时候进行了更新

转载 作者:行者123 更新时间:2023-11-29 16:31:37 25 4
gpt4 key购买 nike

我目前在我的应用程序中使用 PureComponent 父组件和子组件。我预计 PureComponent 仅在状态或 Prop 发生变化时才会更新。为了确保这一点,我让一个子组件在每次调用它的 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(
....
);
}

例如,当父组件中 item2 的状态发生变化时,子组件将记录“Child Updated”。我有点困惑,因为子组件没有接收 item1 作为 Prop ,并且它的状态没有改变。发生这种情况是因为父组件重新渲染了它的所有子组件吗?或者也许是因为 Child 对其 myList 属性所做的浅比较表明它已经改变了?除了编写自己的 shouldComponentUpdate() 方法之外,如何防止每次父级重新渲染时子级都重新渲染?

最佳答案

现在,在 Parent 组件的 render 函数中,您正在使用 combinedList 在每个渲染上创建一个新数组。 PureComponent 切换您的 shouldComponentUpdate() 方法来进行浅比较,以查看它是否应该更新。由于它很浅,它正在比较引用文献。

由于您要在每次渲染时创建一个新数组,因此每次 Parent 渲染时它都会是新的。

这里的解决方案实际上取决于您对combinedList的完整用例。直接看这个例子,我建议你在状态中设置combinedList。另一种选择是将子组件 Prop 拆分为 list1list2 Prop ,而不是 myList Prop 。

关于javascript - React PureComponent 在不应该更新的时候进行了更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com