Redux 业务逻辑最佳实践

Redux business logic best practice

我正在使用 React 和 Redux 构建购物车,但未能理解最佳实践流程。

我的购物车操作:

export const addToCart = (product) => (dispatch, getState) => {
  let { products: cartProducts } = getState().cart;
  let { newCartProducts, totalPrice } = handleAddToCart(cartProducts, product);
  dispatch(
    add({
      products: newCartProducts,
      total: totalPrice,
    })
  );
};

模拟服务器处理程序:(更新产品的所有逻辑都在这里 => 我的主要问题是这是否有意义。

export function handleAddToCart(cartProducts, currentProduct) {
  let idx = cartProducts.findIndex((p) => p.id === currentProduct.id);
  let productInCart = cartProducts[idx];
  if (productInCart) {
    let updatedProduct = {
      ...currentProduct,
      quantity: productInCart.quantity + 1,
      price:
        productInCart.price +
        applySale({
          ...currentProduct,
          quantity: productInCart.quantity + 1,
          currentTotal: productInCart.price,
        }),
    };
    cartProducts.splice(idx, 1, updatedProduct);
  } else cartProducts.push({ ...currentProduct, quantity: 1 });
  let totalPrice = cartProducts.reduce((acc, val) => (acc += val.price), 0);
  return { newCartProducts: cartProducts, totalPrice };
}

大车减速器:


};
export default (state = DEFAULT_STATE, action) => {
  switch (action.type) {
    case "ADD_TO_CART":
      return {
        products: [...action.payload.products],
        total: action.payload.total,
      };

    default:
      return DEFAULT_STATE;
  }
};

正如您从代码中看到的那样,我将操作和缩减程序逻辑保持在最低限度,并让处理程序处理数据。只有在数据被操作之后,我才将其插入状态。 在考虑之后,reducer ADD_TO_CART 只是象征性的,因为它得到一个数组而不是一个项目,所以它实际上可以是一个多用途的 reducer,我认为这不是很好。 很高兴听到更多意见。

我们特别推荐putting as much logic as possible into reducers, and treating actions as "events" that describe "what happened" with the minimal amount of data inside

此外,请注意您应该使用 our official Redux Toolkit package,这将大大简化您的 Redux 逻辑。