Javascript 在ReactJS中的嵌套映射中断原始对象结构上设置状态
我有一个对象数组,如果它与Javascript 在ReactJS中的嵌套映射中断原始对象结构上设置状态,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个对象数组,如果它与type和key匹配,我想添加/更改一个新属性 [ { "type": "a", "units": [ { "key": "keyofba" }, { "key": "mytargetkey" } ] }, { "type": "b", "units": [ { "key": "keyofb" }
type
和key
匹配,我想添加/更改一个新属性
[
{
"type": "a",
"units": [
{
"key": "keyofba"
},
{
"key": "mytargetkey"
}
]
},
{
"type": "b",
"units": [
{
"key": "keyofb"
}
]
},
{
"type": "ab",
"units": [
{
"key": "mytargetkey"
}
]
}
]
我试过这个
this.setState({
schema: schema.map(s => {
if (s.type === 'a' || s.type === 'ab') { //hardcord for testing
return s.units.map(unit => {
if (unit.key === 'mytargetkey') {
return {
...unit,
newProp: 'newProp value'
}
} else {
return { ...unit }
}
})
} else {
return { ...s }
}
})
但不知何故,它不起作用,我想我错过了一些东西,需要spotter。这是因为您必须返回在新对象中修改的列表,如果不是目标,则按原样返回元素:
schema.map(s => {
if (s.type === 'a' || s.type === 'ab') { //hardcord for testing
return {...s, units: s.units.map(unit => {
if (unit.key === 'mytargetkey') {
return {
...unit,
newProp: 'newProp value'
}
} else {
return unit
}
})}
} else {
return s
}
})
@DanielLizik你不需要在地图上打{…s}或{…unit}不客气,别忘了投票!(如果您觉得有用,请接受:D)一个问题,对于else条件,顺便问一下,返回s与返回{…s}有什么不同?