簡體   English   中英

NGRX - 如何通過減速器更新數組中對象中的字段?

[英]NGRX - How to update a field in an object in an array by reducer?

如何通過reducer更新數組中的字段? 我試過這個:

const customers = state.filteredCustomers;
for (const customer of customers) {
    for (const addr of customer.addresses) {
         addr.selected = false;
    }
}

return {
    ...state,
    filteredCustomers: customers,
};

但它拋出一個錯誤:

 TypeError: Cannot assign to read only property 'selected' of object '[object Object]'

做這個的最好方式是什么?

該錯誤似乎是對某些不可變引用進行變異的錯誤之一。 我會嘗試這樣的事情。

    const customers = state.filteredCustomers;

    const updatedCustomers = customers.map( customer => ({
...customer, addresses: customer.addresses.map( address => ({ ...address, selected: false 
}));

    return {
        ...state,
        filteredCustomers: { ...state.filteredCustomers, ...updatedCustomers  },
    };

您可以使用 map 返回具有更新值的新客戶數組。

return {
  ...state,
  filteredCustomers: customers.map(customer => {
    // Either use a second map or another loop
    for (const addr of customer.addresses) {
      addr.selected = false;
    }
    return customer;
  })
};

您將必須復制狀態的每個級別。 在這里,更新 x 級深度的嵌套狀態會變得很尷尬。 這就是為什么我會鼓勵你的 state 正常化

基本上,您必須遍歷客戶並復制屬性,接下來您必須對地址執行相同操作並將 selected 設置為 false。

return {
    ...state,
    filteredCustomers: state.filteredCustomers.map(c => ({
       ...c,
       addresses: c.adresses.map(a => ({...a, selected: false})
    })
};

第二種選擇是使用 immer,Clean NgRx reducers using Immer有一個庫可以為 NgRx 8 中的createReducer函數執行此操作 - https://github.com/timdeschryver/ngrx-etc/#mutableon 通過這種方法,您可以使用問題中發布的代碼片段。

import _ from 'lodash';

並在您的代碼中使用

const tags: IAreaTag[] = _.cloneDeep(department.tags);

然后返回常量

所以在你的代碼中

const customers = _.cloneDeep(state.filteredCustomers);

暫無
暫無

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

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