简体   繁体   English

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

[英]Change property in array with Spread Operator returns object instead of array

I want to change the property of an object similar to this, this is a simplified object with a few properties of the original: 我想更改类似于此的对象的属性,这是一个简化的对象,具有原始的一些属性:

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

I'm changing the state of enabled like this: 我正在改变启用状态,如下所示:

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

It works, but instead of return an array like I is the pivotComuns property it returns an object, "notice that I change [] for {}": 它可以工作,但是返回一个像我这样的数组是pivotComuns属性,它返回一个对象,“注意我为{}更改了[]”:

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

What I'm doing wrong, I need to keep that property an array. 我做错了什么,我需要保持该属性为数组。

Very late post, but for future reference, you could do the following: 帖子很晚,但为了将来参考,您可以执行以下操作:

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

The advantage is that you will not change the object referenced in the "old array", you will instead insert a new object in its place. 优点是您不会更改“旧数组”中引用的对象,而是在其位置插入新对象。 So if you would like to go back and forth in the state you can now do so. 因此,如果你想在州内来回走动,你现在可以这样做。

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

I don't believe you can use the spread operator in such a way and in fact wouldn't recommend it if you could because it creates very hard to read code. 我不相信你可以以这种方式使用扩展运算符,事实上如果你可以不推荐它,因为它会创建非常难以阅读的代码。 There is a much simpler solution that I use on a daily basis when it comes to updating a key/value on an object where the value is an array: 在更新值为数组的对象上的键/值时,我每天都会使用一个更简单的解决方案:

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
 }

this will get you the right results and will not cause any mutations. 这将为您提供正确的结果,不会导致任何突变。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM