【问题标题】:How can I change an object value in an array in react redux reducer state?如何在 react redux reducer 状态下更改数组中的对象值?
【发布时间】:2020-05-17 18:49:46
【问题描述】:

这是我的 react redux reducer

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。 我该怎么做??

【问题讨论】:

  • 这很奇怪,但您不想在 BUY_CAKE 操作中更新 products 数组中的第二项
  • 只需返回一个新状态,其中包含您想要变异的任何内容。但是,一旦 BUY_CAKE 动作被调度,为什么不放置一个新属性“carts”并推送“Cake”呢?

标签: javascript arrays reactjs redux state


【解决方案1】:

假设action.payload 等于对象{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;
    }
};

【讨论】:

    【解决方案2】:

    您可以简单地使用 map 函数,它遍历所有对象并找到有效负载名称并将 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:
                return {
                    ...state,
                    products:state.products.map(item=>{
                         if(item.name===action.payloadName)
                           item.inCart=true
                         return item
                    })
                };
            default:
                return state;
        }
    };

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 2019-02-03
      • 2019-05-07
      相关资源
      最近更新 更多