【发布时间】:2018-08-01 06:31:00
【问题描述】:
我在 Google 和 SO 上搜索了解决方案,但仍然找不到答案。他们都停留在“将商品添加到购物车”或“增加/减少数量”上,但从不计算总计,这很烦人!
在我的应用程序中,有一个商品列表,用户可以在其中输入商品的数量,这会更新其价格。 我想知道的是,您如何使用 Redux 将购物车中所有商品的所有价格汇总为 Total 价格并将其显示在我的 React 应用程序中?
另外,如果你能指出任何好的购物车教程,而不仅仅是在购物车中列出产品,我会很高兴。
行动:
/**
* @description UPDATE SINGLE ITEM PRICE WHEN USER ENTER QUANTITY
*
* @param{number} price
* @param{number} quantity - enter by user from input
*/
export const updateItemPrice = (price, quantity) => dispatch => {
const result = price * quantity;
return dispatch({
type: UPDATE_ITEM_PRICE,
subtotal: result
});
};
减速机:
const INITIAL_STATE = {
total: 0,
subtotal: 0
};
const productsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
// Update single item price
case Types.UPDATE_ITEM_PRICE:
return {
...state,
subtotal: action.subtotal,
total: // --> Here is where I'm stuck!!
};
default:
return state;
}
};
【问题讨论】:
-
商店不应该计算任何东西,这不是它的责任。而是通过操作的状态提供总数。
-
想法是,每当您从购物车中添加或删除商品时,您都应该更新 totalPrice。在 initialState 中将 totalPrice 保持为零。在 reducer 中,每当您删除项目时,都会降低价格并与添加项目相同
标签: javascript reactjs redux react-redux