简体   繁体   English

重构 javascript 代码 react redux 问题

[英]Refactoring javascript code react redux issue

I've code like below.我有如下代码。 No deep knowledge in javascript.对javascript没有深入的了解。 Want to add some product in redux.想在 redux 中添加一些产品。 My reducer initial definition is below我的减速器初始定义如下

const initState = {
    order: {
        item1: [],
        item2: [],
        item3: [],
      }
    }

To add different items to the cart I'm using below function.要将不同的项目添加到购物车,我正在使用以下功能。 Every item will be a list of object每个项目都将是一个对象列表

    const addToCart = (state, action) => {
    if (action.payload.service === 'item1') {
        return {
            ...state,
            order: {
                ...state.order,
                item1: [...state.order.item1, action.payload.item]
            }
        }
    } else if (action.payload.service === 'item2') {
        return {
            ...state,
            order: {
                ...state.order,
                item2: [...state.order.item2, action.payload.item]
            }
        }
    }
}

can it be done in a single code dynamically without condition?可以在没有条件的情况下动态地在单个代码中完成吗? My order will be like below我的订单将如下所示

order: {
        item1: [{'name': 'name1', 'quantity': 2}, {'name': 'name3', 'quantity': 5}],
        item2: [],
        item3: [],
      }

I believe that for you to take out the conditional statement, assuming that the name of the key of the order is the same as the service name from your payload, you can access and assign the key by passing the value from the payload itself.我相信对于你取出条件语句,假设订单的key的名称与你的payload中的服务名称相同,你可以通过从payload本身传递值来访问和分配key。 So instead of something like you have in the reducer, you will get something like this:因此,您将得到如下内容,而不是像您在减速器中那样的东西:

 const addToCart = (state, action) => { return { ...state, order: { ...state.order, [action.payload.service]: [...state.order[action.payload.service], action.payload.item] } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM