这是我的减速减速器之一,我觉得它看起来非常难看。有没有可能改进它?如何让这段代码看起来更好
,我想达到的目的很简单:
如果我已经在我目前的状态这个项目,由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