React 状态数组 updates/renders 整个数组,是否有解决方法?

React state array updates/renders entire array, is there a work-around?

这是基本的想法...

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) 它是否重新渲染 EVERY 组件(在映射数组中),或者它是否足够聪明,可以判断作为 props 传递给映射组件的状态值是一样吗?

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 节点上的类名。

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