小编典典

反应:当状态是对象数组时更新状态

reactjs

我处于状态的对象数组:

this.state = {
  items: [
    {id: 1, someattr: "a string", anotherattr: ""},
    {id: 2, someattr: "another string", anotherattr: ""},
    {id: 3, someattr: "a string", anotherattr: ""},
  ]
}

我需要能够基于id属性搜索items数组,然后更新对象属性。

我可以使用id参数通过数组filteringfinding在数组上获取对象。

我遇到的麻烦是更新数组,然后更新状态而不会发生突变。

//make sure we're not mutating state directly by using object assign
const items = Object.assign({}, this.state.items);
const match = items.find((item) => item.id === id);

此时,我有一个匹配的对象,可以使用对象传播来更新它的属性:

const matchUpdated = { ...match, someattr: 'a new value'};

我的问题是我该如何更新状态,matchUpdated以使其覆盖初始查找操作返回的对象?


阅读 337

收藏
2020-07-22

共1个答案

小编典典

您的更新功能如下所示

updateItem(id, itemAttributes) {
  var index = this.state.items.findIndex(x=> x.id === id);
  if (index === -1)
    // handle error
  else
    this.setState({
      items: [
         ...this.state.items.slice(0,index),
         Object.assign({}, this.state.items[index], itemAttributes),
         ...this.state.items.slice(index+1)
      ]
    });
}

你这样使用它

this.updateItem(2, {someattr: 'a new value'});

毛吧?


如果您继续以这种方式构建复杂的应用程序,通常会头疼。我建议您研究一下redux或其他更适合解决这些问题的Flux实现。

Redux使用状态缩减器的概念,每个都在应用程序状态的特定部分上工作。这样,您就不必在每次要影响重大更改时都手动挖掘整个状态。

Redux的创建者Dan Abramov已免费在线提供了两个视频课程。Dan是一位出色的老师,在度过一个下午之后,我对Redux模式感到满意。

2020-07-22