Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ReactJS中的嵌套映射中断原始对象结构上设置状态_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

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}有什么不同?