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

时间:2016-11-10 04:09:08

标签: javascript reactjs redux immutable.js reducers

这是我的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',
      },
    },
}

2 个答案:

答案 0 :(得分:1)

这就是我如何在语法上增强它:

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;
  }
};

答案 1 :(得分:0)

使用immutable.js处理深层嵌套对象时,我发现了相同的复杂性。我创建了一个轻量级的不可变助手:ImmutableAssign,它允许您继续使用普通的JS对象,这将简化您的操作。

在以下示例中,它希望状态操作是纯JS对象,并且它将返回新状态作为普通JS对象:

function globalReducer(state = initialState, action) {
    switch (action.type) {
        case ADD_TO_CART: return addCart(state, action);
        default: return state;
    }
}

function addCart(state, action) {               
    let { item } = action;

    return iassign(state, 
        function(state, context) {                    
            return state.sideCart.orderItems[context.item.id] 
        },
        function(selectedItem) { 
            item.quantity = selectedItem.quantity ? selectedItem.quantity + 1 : 1;                
            return item;
        },            
        { item: item });
}


// The first parameter is a function that return the 
// property you need to modify in your state.
// This function must be **pure function**, therefore "item" 
// need to be passed in via the context parameter. 
// 
// The second parameter is a function that modify selected 
// part of your state, it doesn't need to be pure, therefore 
// you can access "item" directly
//
// The third parameter is the context used in the first 
// function (pure function)