reactjs – React:当state是一个对象数组时更新状态
我有一个状态的对象数组:
this.state = { items: [ {id: 1,someattr: "a string",anotherattr: ""},{id: 2,someattr: "another string",{id: 3,] } 我需要能够根据id属性搜索items数组,然后更新对象属性. 我可以通过使用id param过滤或查找数组来获取对象. 我遇到的问题是更新阵列,然后更新状态而不会发生突变. //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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |