簡體   English   中英

使用Spread Operator更改數組中的屬性返回對象而不是數組

[英]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
              }
            }
          }

它可以工作,但是返回一個像我這樣的數組是pivotComuns屬性,它返回一個對象,“注意我為{}更改了[]”:

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?edit = 1111

我不相信你可以以這種方式使用擴展運算符,事實上如果你可以不推薦它,因為它會創建非常難以閱讀的代碼。 在更新值為數組的對象上的鍵/值時,我每天都會使用一個更簡單的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM