Redux 业务逻辑最佳实践

Con*_*ght 1 logic frontend flux reactjs redux

我使用 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,
    })
  );
};

Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)

推车减速机:


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

Run Code Online (Sandbox Code Playgroud)

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

mar*_*son 5

我们特别建议将尽可能多的逻辑放入减速器中,并将操作视为“事件”,用最少的数据量描述“发生了什么”

另请注意,您应该使用我们的官方 Redux Toolkit 包,这将大大简化您的 Redux 逻辑。

  • 除此之外,“cartProducts.splice()”和“cartProducts.push()”正在改变“state.cart.products”数组。使用工具包来处理更新可以避免此类错误。我还认为从选择器中派生“total”更有意义,但也许这只是我的看法。 (2认同)