【问题标题】:Change property in array with Spread Operator returns object instead of array使用扩展运算符更改数组中的属性返回对象而不是数组
【发布时间】:2017-06-26 11:57:14
【问题描述】:

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

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

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

【问题讨论】:

  • 您的原始代码缺少{...
  • @Aaron 不仅是{,在对象数据中也缺少,
  • 对,我已经更新了代码。

标签: javascript reactjs redux react-redux spread-syntax


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

    • @DiegoUnanue codepen 在我不想要的时候保存了我现在改回来应该很好
    猜你喜欢
    • 1970-01-01
    • 2021-05-15
    • 2019-09-01
    • 2017-11-15
    • 2017-03-17
    • 2023-01-12
    • 2020-03-18
    • 2018-02-21
    相关资源
    最近更新 更多