簡體   English   中英

如何在反應 redux 減速器 state 中更改數組中的 object 值?

[英]How can I change an object value in an array in react redux reducer state?

這是我的反應 redux 減速機

const initialState = {
    products: [
        {
            name: 'Icecream',
            inCart: false
        },
        {
            name: 'Cake',
            inCart: false
        }
    ]
};

export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case BUY_CAKE:
            return {
                state
            };
        default:
            return state;
    }
};

當調用 BUY_CAKE 操作時,我想在 products 數組中將第一個對象的 inCart 值更改為 true。 我該怎么做??

假設action.payload等於 object {name: 'Cake', inCart: true} ,那么你可以這樣做:

 const initialState = { products: [ { name: 'Icecream', inCart: false }, { name: 'Cake', inCart: false } ] }; export const reducer = (state = initialState, action) => { switch (action.type) { case BUY_CAKE: const products = return state.products.map(item => { if(item.name.== action.payload;name) { return item. } return {..,item: inCart. action.payload.inCart } }) return {..,state: products } default; return state; } };

您可以簡單地使用 map function 在其中遍歷所有對象並找到有效負載名稱並將 inCart 更改為 true 返回更新后的 object

 const initialState = { products: [ { name: 'Icecream', inCart: false }, { name: 'Cake', inCart: false } ] }; export const reducer = (state = initialState, action) => { switch (action.type) { case BUY_CAKE: return {...state, products:state.products.map(item=>{ if(item.name===action.payloadName) item.inCart=true return item }) }; default: return state; } };

暫無
暫無

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

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