首页 > 解决方案 > 如何更改内部状态的数组

问题描述

我想results通过推送新数据来更新!!!

data 是状态数组中的一个数组,

 this.state = {

      comments: {
        results: []
      }
    }; 


 const new = {user : "users"};
 var comments= this.state.comments.results[0].data;
 var  comment= data.push(new);

标签: reactjs

解决方案


这里的其他答案过于复杂。只需这样做:

this.state = {
  comments: {
    results: []
  }
}; 
const new = {user : "users"};
var comments = this.state.comments.results[0].data;
this.setState({
  comments: {
    ...this.state.comments,
    results: [
      ...this.state.comments.results,
      new
    ]
  }
});

...扩展运算符)基本上只获取对象/数组的所有属性/元素并将它们转储到包含的对象/数组中。对于对象,在展开操作之后定义的任何附加属性,如果它们的键相同,则将覆盖由展开添加的属性。


推荐阅读