【发布时间】:2020-11-21 20:19:01
【问题描述】:
我不知道为什么我连草稿都修改了,immer 并没有给我提供新的状态,而是旧的状态实例修改了内容。
import CartItem from "../../models/cart-item";
import * as actions from "../actions/actionTypes";
import produce from "immer"
const initialState = [];
const reducer = (state=initialState, action) => {
switch (action.type) {
case actions.ADD_TO_CART:
const {id, title, price} = action.product;
const itemIndexInCart = state.findIndex(item => item.id === id);
const nextState = produce(state, draftState => {
if (itemIndexInCart === -1) {
draftState.push(new CartItem(id, 1, price, title, price));
} else {
draftState[itemIndexInCart]['quantity']++;
draftState[itemIndexInCart]['sum'] += price;
}
});
console.log(state === nextState);
return nextState;
default:
return state;
}
};
export default reducer;
当新项目被推入数组时它正在工作,但是当我想修改数组项目的数量和总和时它没有按预期工作。日志显示在这种情况下它是同一个对象。
【问题讨论】:
-
也许您应该在
produce回调中从draftState中找到项目ID。在produce回调中,在条件之前尝试const itemIndexInCart = draftState.findIndex(item => item.id === id); -
不,它不起作用,实际上 nextState 已更新,但不知何故它共享了对状态的内存引用。