【发布时间】:2022-01-05 02:37:10
【问题描述】:
首先我不得不提一下,我对反应有点陌生,但我花了几个小时来解决useReducer 的问题,但我无法理解。这是我的代码:
const defaultCartState = {
items: [],
totalAmount: 0,
};
//action = {type:"ADD" , item:item}
const cartReducer = (state, action) => {
if (action.type === "ADD") {
const updatedTotalAmount = parseFloat(
state.totalAmount + action.item.price * action.item.amount
).toFixed(2);
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.item.id
);
const existingCartItem = state.items[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
const updatedItem = state.items[existingCartItemIndex];
updatedItem.amount =
state.items[existingCartItemIndex].amount + action.item.amount;
const updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
} else {
const updatedItems = state.items.concat(action.item);
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
}
return defaultCartState;
};
它只是我的减速器函数state 包含一个名为items 的数组,该数组的每个元素都是一个具有amount 值的对象。这是我的useReducer 初始化:
const [cartState, dispatchCartAction] = useReducer(cartReducer,defaultCartState);
我的问题在于这两行代码:
if (existingCartItem) {
const updatedItem = state.items[existingCartItemIndex];
updatedItem.amount =
state.items[existingCartItemIndex].amount + action.item.amount;
如果我将这两行代码换成这些,一切正常。
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + action.item.amount,
};
我想知道是什么问题?为什么我的方法不起作用?定义像我的解决方案这样的项目和真正的解决方案有什么区别? 提前谢谢你
【问题讨论】:
标签: reactjs react-hooks use-reducer