简体   繁体   中英

How to update array element using setState in React?

If I had an array structure similar to this:

person[{id: 0, firstname: 'john', surname: 'smith'}, 
       {id: 1, firstname: 'jane', surname: 'smith'}]

Then using an event handler to catch some change and using setState, how could I update the array element similar to this:

handleChangeEvent(newSurname, id){
     this.setState({ person[id].surname : newSurname})
}

Use setState() 's updater callback to perform your state change in a single atomic operation without the risk of overwriting (or being overwritten by) other state changes to the component in the same event tick:

handleChangeEvent(surname, id) {
    this.setState(({ people }) => ({
        people: people.map(
            person => person.id === id ? { ...person, surname } : person
        )
    }));
}

Perhaps you could try something along the lines of:

handleChangeEvent(newSurname, id){
  this.setState(prevState => ({
    people: prevState.people.map(
      person => person.id === id ? { ...person, surname: newSurname } : person
    )
  }));
}

In this code snippet we are getting a reference to your people array in your component's state. Then we are filtering this array based on ids and if the id matches the person whose name needs to be updated we set the surname appropriately. Otherwise, we just return the existing object if the id doesn't match the person who needs to be updated.

Hopefully that helps!

This is basically what you are looking for. I'd however recommend you to use a library like immer to create immutable objects.

handleChangeEvent(newSurname, id){
     this.setState({
                     people : Array.from(this.state.people, person => {
                          if(person[id] === id)
                           return {...person, surname: newSurname}
                          return person
                     })   
     })
}

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