使用 setState() 将对象添加到对象数组 [英] Add an object with setState() to an array of objects

查看:87
本文介绍了使用 setState() 将对象添加到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件的状态是一个对象数组:

My component's state is an array of objects:

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

我需要,每次我点击一个按钮时,用另一个对象更新我的状态,就像我在上面的状态中一样;例如:{id: 3, title: 'C'}.

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'}.

如果我简单地连接它们并设置状态,最后一个对象会不断被添加的对象改变.

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?

推荐答案

你应该这样做.下面是最推荐的在 react 中将值或对象推送到数组的方法

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]
  }));

这篇关于使用 setState() 将对象添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆