我正在使用 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;
}
};
正如您从代码中看到的,我将操作和化简器逻辑保持在最低限度,并让处理程序操纵数据。只有在数据被操作之后,我才将其插入到状态中。 经过深思熟虑,减速器 ADD_TO_CART 只是象征性的,因为它获取的是一个数组而不是一个项目,所以它实际上可以是一个多用途减速器,我认为这不太好。 很高兴听到更多意见。
我们特别建议将尽可能多的逻辑放入reducer中,以及将动作视为“事件”,用最少的数据来描述“发生了什么”。
另外,请注意,您应该使用 我们的官方 Redux Toolkit 包,这将大大简化您的 Redux 逻辑。
这在现代 React 生态系统中被认为是反模式。
根据单一责任原则。 使用自定义挂钩以简单的方式保持业务逻辑(如果需要,请在其中使用原型继承),要存储 API 调用,请使用 Tanstack 查询,并使用 Jotai (Atoms) 存储全局数据。这个库非常容易学习和维护。
您现在不需要编写 Redux(action、reducers 和 store)、Redux 工具包和其他样板代码。即使您学习了这个概念,它在其他堆栈中也没有那么有用。
即使在今天,许多工作要求都要求 Redux 问题,我希望他们能够尽快用提到的最佳实践更新他们的项目。