gpt4 book ai didi

reactjs - React 状态数组更新/渲染整个数组,有解决方法吗?

转载 作者:行者123 更新时间:2023-12-03 13:35:33 25 4
gpt4 key购买 nike

这是基本思想...

constructor(props) {
super(props);
this.state = {
children: [{id:1},{id:2}], // HERE ARE THE TWO OBJECTS
style: {top: 0}
};
}

现在假设我更新了这两个对象之一,但这些对象被映射到组件数组。

<div className="thread">
{this.state.children.map((child) =>
<Post
key={child.id}
id={child.id}
/>
)}
</div>

现在...当我更新其中一个对象时...

changeID (id, newID) { // this is a different function, just an example
let temp = this.state.children;
for (let i = 0; i < temp.length; i++) {
if (temp[i].id === id) {
temp[i].id = newID; // <- update this
}
}
this.setState({
children: temp // <- plug temp[] back as the updated state
});
}

我将新状态放回原处,但它会更新每个映射的对象。

// on one change to one element
id 1 POST UPDATED
id 2 POST UPDATED

1)它是否重新渲染每个组件(在映射数组中),或者它是否足够智能来告诉作为 Prop 传递给映射组件的状态值是相同的?

2)如果该阵列明显更长,处理能力是否会非常昂贵?

3)如果是,我怎样才能更好地解决这个问题?欢迎提出建设性批评。

谢谢!

最佳答案

这就是react的工作原理,每当你更改任何state变量时,它都会重新渲染完整的组件并更新虚拟dom而不是实际dom,然后它会检查两者之间的差异并仅更改实际 dom 中的特定元素。

根据DOC :

React provides a declarative API so that you don't have to worry about exactly what changes on every update.

<强> React Only Updates What's Necessary:

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

<强> DOM Elements Of The Same Type:

When comparing two React DOM elements of the same type, React looks at the attributes of both, keeps the same underlying DOM node, and only updates the changed attributes.

例如:

<div className="before" title="stuff" />

<div className="after" title="stuff" />

通过比较这两个元素,React 知道只修改底层 DOM 节点上的 className。

<强> Use of Keys :

React supports a key attribute. When children have keys, React uses the key to match children in the original tree with children in the subsequent tree.

Imp:

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity. Keys used within arrays should be unique among their siblings. However they don't need to be globally unique.

例如:

<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>

<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>

现在 React 知道键为“2014”的元素是新元素,而键为“2015”和“2016”的元素刚刚移动。

查看这篇文章:How Virtual-DOM and diffing works in React

关于reactjs - React 状态数组更新/渲染整个数组,有解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44822432/

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