向减速器添加条件是否是反模式?

时间:2018-10-18 16:01:01

标签: redux

我的商店中有购物车商品,我想检查用户是否添加了相同颜色和尺寸的商品。

如果是这样,我只是想增加数量,如果不只是添加它,它会创建一个有点笨拙的减速器,我想知道这是否被视为反模式,如果是的话,我们可以怎么做简化

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

1 个答案:

答案 0 :(得分:1)

不,这绝对不是反模式。 Reducers can, and should, do a lot more than just return {...state, ...action.payload}。现在,您可以根据自己的意愿在化简器中添加什么逻辑,以及在过程中选择使用什么抽象。

如果您担心编写nested immutable update logic,那么建议您看看immer immutable update library。我还建议尝试使用我们内部使用immer的新redux-starter-kit package

相关问题