這是我的減速減速器之一,我覺得它看起來非常難看。有沒有可能改進它?如何讓這段代碼看起來更好
,我想達到的目的很簡單:
如果我已經在我目前的狀態這個項目,由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',
},
},
}
感謝您的幫助@luboskranc如果getIn和setIn是副作用,你將如何處理這種情況? –
'state.setIn'來自Immutable.js並返回一個新狀態,保持以前的狀態不變。所以沒有副作用。 – DDS
好吧,我刪除了我的答案,謝謝 – luboskrnac