简体   繁体   English

ReactJS:如何在数组状态中添加一个新元素并为它们保留“prevState”?

[英]ReactJS: How to add a new element in array state and to preserve "prevState" for them?

My array state is rendering and i can to push new elements without problem, but, when i trying add in specific index, react is changing the state of the previous elements.我的数组状态正在渲染,我可以毫无问题地推送新元素,但是,当我尝试添加特定索引时,react 正在更改先前元素的状态。 Example of the previous state:先前状态的示例:

{this.state.numOfRows.map((v, k) => (
    <Item add={this.add.bind(this)} key={`item-${k}`} index={k} item={v} />
))}

This will render a html element with option = 0;这将渲染一个带有 option = 0 的 html 元素; So, when i call this.add(index) prop i can push 2 or 3 more elements on my array and i change options for 1 and 2. But, when i call this.add(index) to add a new element in index 2, for example, then the previous options that i selected are updated and the new element with 0 in option is displayed in the last index.因此,当我调用 this.add(index) 属性时,我可以在我的数组上再推送 2 或 3 个元素,并更改 1 和 2 的选项。但是,当我调用 this.add(index) 在索引中添加一个新元素时2,例如,然后我选择的先前选项被更新,并且选项中带有 0 的新元素显示在最后一个索引中。

enter image description here在此处输入图片说明

When rendering lists in React, you should specify a key that is based on the unique identity of the item being rendered, rather than the (current) index/position of that item in the source array.在 React 中渲染列表时,您应该指定一个基于正在渲染的项目的唯一标识的key ,而不是该项目在源数组中的(当前)索引/位置。

In your case, if each items in the numOfRows array had a unique identifier (ie someUniqueId as shown below) then this would be a better candidate for use with the key prop of each <Item /> that is rendered:在您的情况下,如果numOfRows数组中的每个项目都有一个唯一标识符(即someUniqueId ,如下所示),那么这将是与呈现的每个<Item />key prop 一起使用的更好候选者:

{
  this.state.numOfRows.map((v, k) => 
      (<Item add={this.add.bind(this)} 
             key={`item-${ v.someUniqueId }`} 
             index={k} 
             item={v} />))
} 

The reason for this is that React determines if an item in a rendered list needs to be updated based on that items key .这样做的原因是 React 确定是否需要根据项目key更新呈现列表中的项目。 Rendering anomalies will arise when an item's key (based on it's index) remains the same despite the actual data for that item changing.尽管该项目的实际数据发生变化,但当项目的key (基于其索引)保持不变时,就会出现渲染异常。

For more information on this, see React's Lists and Keys documentation.有关这方面的更多信息,请参阅 React 的列表和键文档。

Also, see this in-depth article on the key prop and specifically, this summary of when an index based key prop is okay .另外,请参阅这篇关于key prop 的深入文章,特别是关于何时基于索引的 key prop 的总结

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM