2016-11-10 73 views
1

这是我的减速减速器之一,我觉得它看起来非常难看。有没有可能改进它?如何让这段代码看起来更好

,我想达到的目的很简单:

如果我已经在我目前的状态这个项目,由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', 
     }, 
    }, 
} 

回答

1

这是我怎么会语法增强它:用immutable.js深入处理时

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

感谢您的帮助@luboskranc如果getIn和setIn是副作用,你将如何处理这种情况? –

+1

'state.setIn'来自Immutable.js并返回一个新状态,保持以前的状态不变。所以没有副作用。 – DDS

+0

好吧,我删除了我的答案,谢谢 – luboskrnac

0

我发现了同样的复杂性嵌套对象。我做了一个轻量级的不可变帮助器: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)