以不变的方式更新数组中的对象之一 [英] Update one of the objects in array, in an immutable way
问题描述
在React的this.state中,我有一个名为formErrors
的属性,其中包含以下动态对象数组.
In React's this.state I have a property called formErrors
containing the following dynamic array of objects.
[
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
假设我需要将具有fieldName cityId
的状态对象更新为true
的有效值.
Let's say I would need to update state's object having the fieldName cityId
to the valid value of true
.
最简单或最常见的解决方法是什么?
我可以使用任何一种库 immutability-helper , immutable-js 等或ES6.我已经尝试并在Google上搜索了4个多小时,但仍然无法绕开它.非常感谢您的帮助.
I'm OK to use any of the libraries immutability-helper, immutable-js etc or ES6. I've tried and googled this for over 4 hours, and still cannot wrap my head around it. Would be extremely grateful for some help.
推荐答案
您可以使用map
迭代数据并检查fieldName,如果fieldName是cityId,则需要更改值并返回新对象,否则只需return
相同的object
.
You can use map
to iterate the data and check for the fieldName, if fieldName is cityId then you need to change the value and return a new object otherwise just return
the same object
.
这样写:
var data = [
{fieldName: 'title', valid: false},
{fieldName: 'description', valid: true},
{fieldName: 'cityId', valid: false},
{fieldName: 'hostDescription', valid: false},
]
var newData = data.map(el => {
if(el.fieldName == 'cityId')
return Object.assign({}, el, {valid:true})
return el
});
this.setState({ data: newData });
这篇关于以不变的方式更新数组中的对象之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!