2016-11-10 74 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)