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

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

问题描述

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

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使用状态减少器的概念,每个状态减少器都在应用程序状态的特定部分上工作.这样一来,您就不必在每次要影响重大更改时都手动挖掘整个状态.

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.

  • https://egghead.io/courses/getting-started-with-redux
  • https://egghead.io/courses/building-react-applications-with-idiomatic-redux

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

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