Redux 向减速器添加条件是反模式吗?
我的商店里有一个购物车项目,我想检查用户是否添加了相同颜色和大小的相同项目 如果是这样的话,我只想增加数量,如果不只是添加,而是创建一种akward减速器,我想知道这是否被视为反模式,如果是,我们可以做什么来简化它Redux 向减速器添加条件是反模式吗?,redux,Redux,我的商店里有一个购物车项目,我想检查用户是否添加了相同颜色和大小的相同项目 如果是这样的话,我只想增加数量,如果不只是添加,而是创建一种akward减速器,我想知道这是否被视为反模式,如果是,我们可以做什么来简化它 export default (state = initialState, action) => { switch (action.type) { case 'ADD_TO_CART': // Check to see if we already hav
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_TO_CART':
// Check to see if we already have the same product
// with the same color and size in our cart
const productIndex = state.products
.findIndex(product => product._id === action.product._id
&& product.size === action.product.size
&& product.color === action.product.color);
// if we have it already increase the quantity
if (productIndex !== -1) {
const updatedProduct = {
...state.products[productIndex],
quantity: state.products[productIndex].quantity + action.product.quantity,
};
return {
...state,
products: [
...state.products.slice(0, productIndex),
updatedProduct,
...state.products.slice(productIndex + 1),
],
};
}
// if not just save it
return {
...state,
products: [...state.products, action.product],
};
default:
return state;
}
};
不,这绝对不是反模式。现在,您在减速器中放入什么逻辑取决于您,以及您选择在流程中使用什么抽象
如果你关心写作,那么我建议你看看。我还建议尝试我们的新产品,它在内部使用immer