简体   繁体   English

使用 setState() 将对象添加到对象数组

[英]Add an object with setState() to an array of objects

My component's state is an array of objects:我的组件的状态是一个对象数组:

this.state = {
  userFavorites: [{id: 1, title: 'A'}, {id: 2, title: 'B'}]
}

I need to, everytime I click in a button, update my state with another object like the ones I have in my state above;每次单击按钮时,我都需要使用另一个对象更新我的状态,就像我在上面的状态中一样; for example: {id: 3, title: 'C'}.例如:{id: 3, title: 'C'}。

If I simply concat them and set the state, the last object keeps being changed by the one that's being added.如果我简单地连接它们并设置状态,最后一个对象会不断被添加的对象更改。

Do I need the spread operator here?我在这里需要点差运算符吗?

You should do it this way.你应该这样做。 Below is the most recommended way to push values or objects to an array in react以下是在反应中将值或对象推送到数组的最推荐方法

 this.setState( prevState => ({
     userFavorites: [...prevState.userFavourites,  {id: 3, title: 'C'}]
 }));

To push to the beginning of the array do it this way要推送到数组的开头,请这样做

   this.setState( prevState => ({
     userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
  }));
const userFavorites = [...this.state.userFavorites, {id: 3, title: 'C'}]
this.setState({ userFavorites })

There are multiple ways to do this.有多种方法可以做到这一点。 The simplest way for what you are needing to do is to use the spread operator.您需要做的最简单的方法是使用扩展运算符。 Note that item is the object being added to userFavorites.请注意, item 是添加到 userFavorites 的对象。

this.setState({
  userFavorites: [ ...this.state.userFavorites, item ],
});

Note: If at some point down the line you are needing to update a specific item in the array, you could use the update function from the immutability-helpers library.注意:如果在某个时候你需要更新数组中的特定项目,你可以使用 immutability-helpers 库中的更新函数。 https://reactjs.org/docs/update.html https://reactjs.org/docs/update.html

对于功能组件

setUserFavorites((prev) => [...prev, {id: 3, title: 'C'}])

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

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