当状态是对象数组时更新 React 状态

2023-12-02

我有一个处于状态的对象数组:

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

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

我可以通过以下方式获取对象filtering or finding使用 id 参数在数组上。

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

//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以便它覆盖初始查找操作返回的对象?


你的更新函数看起来像这样

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 模式感到很舒服。

  • https://egghead.io/courses/getting-started-with-redux
  • https://egghead.io/courses/building-react-applications-with-idiomatic-redux
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当状态是对象数组时更新 React 状态 的相关文章

随机推荐