首页 > 解决方案 > 嵌套地图上的setState打破ReactJS中的原点对象结构

问题描述

我有一个对象数组,我想添加/更改一个新属性,因为它匹配typekey

[
  {
    "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 }
    }
})

但不知何故它不起作用,我想我错过了一些东西,需要观察者。

标签: javascriptreactjsecmascript-6

解决方案


那是因为您必须返回在新对象中修改的列表,如果不是目标,则按原样返回元素:

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

推荐阅读