简体   繁体   中英

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. 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; 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.

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.

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:

{
  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 . 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.

For more information on this, see React's Lists and Keys documentation.

Also, see this in-depth article on the key prop and specifically, this summary of when an index based key prop is okay .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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