Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

angular - NGRX-如何通过reducer更新数组中对象的字段?(NGRX - How to update a field in an object in an array by reducer?)

How can I update a field in an array by reducer?

(如何通过reducer更新数组中的字段?)

I tried this:

(我尝试了这个:)

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

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

But it throws an error:

(但这会引发错误:)

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

What is the best way to do this?

(做这个的最好方式是什么?)

  ask by Moein Hosseini translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error seems to be one of mutating some immutable reference.

(该错误似乎是使某些不可变的引用发生变异的原因之一。)

I would try something like this.

(我会尝试这样的事情。)

    const customers = state.filteredCustomers;

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...