2

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

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

它可以工作,但不是像我一样返回一个数组,而是 pivotComuns 属性,它返回一个对象,“注意我将 [] 更改为 {}”:

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

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

4

2 回答 2

9

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

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

优点是您不会更改“旧数组”中引用的对象,而是在其位置插入一个新对象。因此,如果您想在该州来回走动,您现在可以这样做。

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

于 2017-08-02T08:00:03.090 回答
1

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

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

于 2017-02-08T18:20:48.553 回答