javascript - 嵌套地图上的setState打破ReactJS中的原点对象结构
问题描述
我有一个对象数组,我想添加/更改一个新属性,因为它匹配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 }
}
})
但不知何故它不起作用,我想我错过了一些东西,需要观察者。
解决方案
那是因为您必须返回在新对象中修改的列表,如果不是目标,则按原样返回元素:
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
}
})
推荐阅读
- marklogic - cts:element-query vs cts:path-range-query 性能
- php - 如果你使用 exclude_if 并且它是 TRUE,Laravel 可以忽略进一步的验证规则吗?
- javascript - Ag-Grid:无法读取属性 0
- hive - RJDBC 配置单元,连接失败
- python - 如何计算 Pandas 中重复频率最高的短语
- azure - 如何在 Azure 中最好地设置 MTLS
- html - 列出未从头开始的项目
- git - 不支持在没有 HEAD 的情况下在 repo 上提交 PhpStorm 设置存储库 - 否
文件夹 - python - Python:重复函数,用一个数字(1~3)替换x,每次传递都会增加
- reactjs - 怎么去掉里面的白色背景
元素