NGRX-如何通过reducer更新数组中对象的字段?

时间:2019-12-01 10:33:53

标签: angular state ngrx reducers

如何通过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]'

最好的方法是什么?

3 个答案:

答案 0 :(得分:0)

该错误似乎是对某些不可变引用进行了变异之一。我会尝试这样的事情。

    const customers = state.filteredCustomers;

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

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

答案 1 :(得分:0)

您可以使用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;
  })
};

答案 2 :(得分:0)

您将必须复制该状态的每个级别。在这里更新x级别的嵌套状态可能很尴尬。这就是为什么我会鼓励normalizing your state

基本上,您将必须遍历客户并复制属性,接下来,您必须对地址进行相同的操作并将其设置为false。

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

第二种选择是使用浸入式Clean NgRx reducers using Immer 在NgRx 8-https://github.com/timdeschryver/ngrx-etc/#mutableon中有一个针对createReducer函数的库。通过这种方法,您可以使用问题中发布的代码段。