【问题标题】:Redux business logic best practiceRedux 业务逻辑最佳实践
【发布时间】:2021-06-21 04:05:03
【问题描述】:

我正在使用 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,我认为它不太好。 很高兴听到更多的意见。

【问题讨论】:

    标签: reactjs redux frontend logic flux


    【解决方案1】:

    【讨论】:

    • 为了补充这一点,cartProducts.splice()cartProducts.push() 正在改变 state.cart.products 数组。使用工具包来处理更新将避免这种错误。我也认为从选择器派生total 更有意义,但也许这就是我。
    猜你喜欢
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多