简体   繁体   English

如何在 React 中使用 setState 更新数组元素?

[英]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:然后使用事件处理程序来捕获一些更改并使用 setState,我如何更新与此类似的数组元素:

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:使用setState()更新程序回调在单个原子操作中执行状态更改,而不会在同一事件滴答中覆盖(或被覆盖)组件的其他状态更改:

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.在此代码片段中,我们将获得对组件状态下的people数组的引用。 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.然后我们根据ids过滤这个数组,如果id匹配需要更新姓名的人,我们会适当地设置surname Otherwise, we just return the existing object if the id doesn't match the person who needs to be updated.否则,如果id与需要更新的人不匹配,我们只返回现有对象。

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.但是,我建议您使用像 immer 这样的库来创建不可变对象。

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

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

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