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

标签 javascript reactjs redux react-redux spread-syntax

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

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

它有效,但它返回一个对象,而不是像 I 那样返回一个数组,它返回一个对象,“请注意我将 [] 更改为 {}”:

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

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

最佳答案

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

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

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

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

关于javascript - 使用 Spread Operator 更改数组中的属性返回对象而不是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120358/

相关文章:

javascript - React-timer 中的解析时间

javascript - 使用useSelector一次或多次有性能差异吗?

javascript - 为什么 $.when().pipe().then() 有效,但 $.when().then().then() 无效?

javascript添加onclick不成功

javascript - Three.js - 从头开始​​重新加载场景

javascript - 在 Debug模式和正常模式之间 react native 不同的行为

reactjs - React-pixi 和 Reagent 导致不变违规

javascript - react-native 如何分配多个 .replace() 作为变量?

reactjs - 如何缓存 API 响应并稍后在 React 和 Redux 中使用它?

javascript - redux store 保存在哪里?