React:当状态是对象数组时更新状态 [英] React: Updating state when state is an array of objects

查看:18
本文介绍了React:当状态是对象数组时更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array of objects in state:

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

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

I need to be able to search the items array based on the id property and then update the objects attributes.

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

I can get the object by filtering or finding on the array using the id param.

我遇到的问题是然后更新数组,然后在没有突变的情况下更新状态.

What I'm having trouble with is then updating the array and then subsequently updating state without mutation.

//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);

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

At this point I have a matching object and can update it's properties using object spread:

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

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

My question is how do i then update the state with matchUpdated so that it overwrites the object returned by the initial find operation?

推荐答案

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

Your update function would look like this

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 实现解决这些问题.

You're going to have a big headache in general if you continue to build a complex application in this manner. I would recommend you look into redux or some other Flux implementation that is better suited for solving these problems.

Redux 使用 state reducer 的概念,每个都在应用程序状态的特定切片上工作.这样您就不必在每次想要影响深层更改时手动挖掘整个状态.

Redux uses a concept of state reducers which each work on a specific slice of the state of your application. That way you don't have to manually dig through your entire state each time you want to affect a deep change.

Redux 的创建者 Dan Abramov 已在网上免费提供了两个视频课程.Dan 是一位出色的老师,在使用 Redux 模式一个下午后,我对它感到很满意.

The creator of Redux, Dan Abramov, has made two video courses available online for free. Dan is an excellent teacher and I felt comfortable with the Redux pattern after spending just one afternoon with it.

这篇关于React:当状态是对象数组时更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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