如何使这段代码看起来更好

如何使这段代码看起来更好

这是我的redux减速器之一,我觉得它很难看。有可能改善吗?

我要实现的目标非常简单:

如果我目前的状态已经有此商品,请将数量增加1,
否则将此项目添加到状态。

function globalReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TO_CART: {
      let { item } = action;
      if (state.getIn(['sideCart', 'orderItems', item.id])) {
        item.quantity = state.getIn(['sideCart', 'orderItems', item.id]).get('quantity') + 1;
      } else {
        item.quantity = 1;
      }
      item = fromJS(item);
      const newState = state.setIn(['sideCart', 'orderItems', item.get('id')], item);
      return newState;
    }
    default:
      return state;
  }
}


状态应如下所示:

sideCart: {
    orderItems: {
      1: {
        id: 'orderItems-1',
        name: 'AI Brown\'s BBQ Fillet of Beef with Brown Mushroom Brandy Sauce',
        quantity: 10,
        price: 12,
        subitems: ['0', '1', '2'],
        instruction: 'No rosemary for beef',
      },
      2: {
        id: 'orderItems-2',
        name: 'AI Brown\'s BBQ Fillet',
        quantity: 10,
        price: 14,
        subitems: ['0', '1', '2'],
        instruction: 'No rosemary for beef',
      },
    },
}

最佳答案

这就是我将在语法上增强它的方式:

const reduceCart = (state, action) => {
  let { item } = action;
  const stateIn = state.getIn(['sideCart', 'orderItems', item.id]);
  item.quantity = stateIn
      ? stateIn + 1
      : 1;
  item = fromJS(item);
  return state.setIn(['sideCart', 'orderItems', item.get('id')], item);
};

const globalReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TO_CART: return reduceCart(state, action);
    default: return state;
  }
};

关于javascript - 如何使这段代码看起来更好,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40519819/

10-12 15:45