Abh*_*hek 2 reactjs react-context
这里我调用了一个函数 addItem,其中我增加了购物车的价值
<CartItem
key={`cartItem-${item.item_id}`}
onIncrement={() => addItem(item)}
onDecrement={() => removeItem(item)}
onRemove={() => removeItemFromCart(item)}
data={item}
/>
Run Code Online (Sandbox Code Playgroud)
我的背景是
const addItemHandler = (item, quantity = 1) => {
dispatch({ type: 'ADD_ITEM', payload: { ...item, quantity } });
};
Run Code Online (Sandbox Code Playgroud)
和我的reducer,用于在reducer.js中添加项目
export const addItemToCart = (state, action) => {
const existingCartItemIndex = state.items.findIndex(
(item) => item.item_id === action.payload.item_id
);
if (existingCartItemIndex > -1) {
const newState = [...state.items];
newState[existingCartItemIndex].quantity += action.payload.quantity;
return newState;
}
return [...state.items, action.payload];
};
const reducer = (state, action) => {
switch (action.type) {
case 'ADD_ITEM':
return { ...state, items: addItemToCart(state, action) };
default:
throw new Error(`Unknown action: ${action.type}`);
}
};
Run Code Online (Sandbox Code Playgroud)
此代码将计数器增加 2,而不是 1。
您的数量增加两次的原因是您将使用React.StrictMode它调用您的减速器两次。
这是有意的行为,有助于检测副作用。你必须注意,如果你的reducer是一个纯函数,这样的效果就不会发生。
在您的情况下,您已经改变了状态中的数量值,这就是您双倍增量的原因。即使您使用扩展语法来复制数组,它也只执行浅复制,并且其中的内部对象仍然保留相同的引用。
要正确更新它,您必须以不可变的方式更新减速器。您可以用于Array.prototype.slice此目的
export const addItemToCart = (state, action) => {
const existingCartItemIndex = state.items.findIndex(
(item) => item.item_id === action.payload.item_id
);
if (existingCartItemIndex > -1) {
const newState = [
...state.items.slice(0, existingCartItemIndex),
{...state.items[existingCartItemIndex], quantity: state.items[existingCartItemIndex].quantity + 1},
...state.items.slice(existingCartItemIndex + 1)
];
return newState;
}
return [...state.items, action.payload];
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1314 次 |
| 最近记录: |