Home > front end >  Is the react keep the old state in the component when rendering web page?
Is the react keep the old state in the component when rendering web page?

Time:01-17

I have a list of items, each item has a state and event handler (I am using the setTimeout to simulate the case.) to update the state.

When I remove item 1 from the list, the state of item 2 becomes "aa0" not "bb" or "N.A".

After the setTimeout function is executed, the state of item 2 resumes normally.

Unfortunately, in my real development environment, the event may not be triggered after the item list is updated.

Would you tell me why? and is there any best practice to fix the problem?

Here is my source code for your reference:

https://stackblitz.com/edit/react-kzjznp

CodePudding user response:

The issue is occurred due to the item key

<Item itemObj={obj} key={index} />

Before removing key for Item component was "0" and "1". After removing the first item, key of the remaining component becomes 0 which refers to the old Item or removed item component and so it is not rendered again.

You can fix it by changing the key. In this case better don't use index, use a unique id instead here you can use item name

<Item itemObj={obj} key={obj.name} />

working code

https://stackblitz.com/edit/react-ldrzai?file=src/ItemList.js

  •  Tags:  
  • Related