使用 Spread Operator returns 对象而不是数组更改数组中的 属性

Change property in array with Spread Operator returns object instead of array

我想更改与此类似的对象的 属性,这是一个简化的对象,具有原始对象的一些属性:

 state = {
    pivotComuns: [
      {
        id: 1,
        enabled : true
      },
      {
      id: 2,
      enabled : true
     }
   ],
   otherProperties : "otherProperties"
 }

我正在像这样更改启用状态:

 state = {
            ...state,
            pivotColumns: {
              ...state.pivotColumns,
              [2]: {
                ...state.pivotColumns[2], enabled: !state.pivotColumns[2].enabled
              }
            }
          }

它有效,但不是 return 像我这样的数组是 pivotComuns 属性 它 return 是一个对象,"notice that I change [] for {}":

state = {
        pivotComuns: {
          {
            id: 1
            enabled : true
          },
          {
          id: 2,
          enabled : true
         }
       },
       otherProperties : "otherProperties"
     }

我做错了什么,我需要将 属性 保留为一个数组。

我认为您不能以这种方式使用展开运算符,实际上如果可以的话也不推荐它,因为它会创建非常难以阅读的代码。在更新值为数组的对象上的 key/value 时,我每天都会使用一个更简单的解决方案:

var state = {
  pivotColumns: [
    {
      id: 1,
      enabled : true
    }, {
    id: 2,
    enabled : true
   }
 ],
 otherProperties : "otherProperties"
}

var clonedPivotColumns = state.pivotColumns.slice();

clonedPivotColumns[1].enabled = !state.pivotColumns[1].enabled;

state = {
   ...state,
   pivotColumns: clonedPivotColumns
 }

这将为您提供正确的结果,并且不会导致任何突变。

工作笔 http://codepen.io/finalfreq/pen/ggdJgQ?editors=1111

很晚了 post,但为了将来参考,您可以执行以下操作:

state = {
   ...state,
   pivotColumns: state.pivotColumns.map(pc => 
    pc.id === 2 ? {...pc, enabled:!pc.enabled} : pc
  )
}

优点是您不会更改 "old array" 中引用的对象,而是在其位置插入一个新对象。所以如果你想在这个州来回走动,你现在可以这样做。

示例: https://codepen.io/anon/pen/JyXqRe?editors=1111