简体   繁体   English

ReactJS中嵌套地图中断原点对象结构上的setState

[英]setState on nested map break origin object structure in ReactJS

I have an array of objects, and I want to add/change a new property given it matches type and key . 我有一个对象数组,并且我想添加/更改一个与typekey匹配的新属性。

[
  {
    "type": "a",
    "units": [
      {
        "key": "keyofba"
      },
      {
        "key": "mytargetkey"
      }
    ]
  },
  {
    "type": "b",
    "units": [
      {
        "key": "keyofb"
      }
    ]
  },
  {
    "type": "ab",
    "units": [
      {
        "key": "mytargetkey"
      }
    ]
  }
]

I tried this 我试过了

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 }
    }
})

But somehow it doesn't work, I think I missed something, need spotter. 但是不知何故,我想我错过了一些东西,需要检查员。

That's because you have to return the list modified inside the new object, and if not it the target, return the element as is: 这是因为您必须返回在新对象内部修改的列表,如果不是目标,则按原样返回元素:

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
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM