问题描述
在 React 的 this.state 中,我有一个名为 formErrors
的属性,其中包含以下动态对象数组.
假设我需要将 fieldName cityId
的 state 对象更新为 true
的有效值.
解决这个问题最简单或最常用的方法是什么?
我可以使用任何库immutability-helper,immutable-js 等或 ES6.我已经尝试并在谷歌上搜索了 4 个多小时,但仍然无法理解它.非常感谢您的帮助.
您可以使用map
来迭代数据并检查fieldName,如果fieldName 是cityId 则需要更改值并返回一个新对象,否则就返回
相同的object
.
这样写:
var 数据 = [{fieldName:'title',有效:false},{fieldName: 'description', 有效: true},{fieldName: 'cityId', 有效: false},{fieldName:'hostDescription',有效:false},]var newData = data.map(el => {if(el.fieldName == 'cityId')返回 Object.assign({}, el, {valid:true})返回 el});this.setState({ data: newData });
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},
]
Let's say I would need to update state's object having the fieldName cityId
to the valid value of true
.
What's the easiest or most common way to solve this?
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.
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
.
Write it like this:
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 });
这篇关于以不可变的方式更新数组中的一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!