为什么这个状态会被 immer produce 突变?
Why is this state mutated by immer produce?
我在使用 Immer 的产品操纵状态时收到状态突变错误。
当我在同一个 reducer 中手动创建一个测试接口并调用 produce 时,它似乎按预期工作:
export interface ItemSliceState {
items: Array<IItem> | null | undefined;
}
export const initialState: ItemSliceState = { items: [] };
export const updateItem: CaseReducer<
ItemSliceState,
PayloadAction<IItem | null | undefined>
> = (state: ItemSliceState = initialState, action) => {
const testItem: IItem = {
status: 1
};
const testItems: Array<IItems> = [testItem];
const testState: ItemSliceState = { items: testItems };
const nextTestState = produce(testState, draftState => {
if (!draftState || !draftState.items) {
return testState;
}
draftState.items[0].status = 2;
});
const nextState = produce(state, draftState => {
if (!draftState || !draftState.items) {
return state;
}
draftState.items[0].status = 2;
});
...
// testState.items[0].status = 1
// nextTestState.items[0].status = 2
// state.items[0].status = 2
// nextState.items[0].status = 2
为什么'state'被操纵,而同样调用produce时'testState'却保持不变?
状态更新正确的沙盒:
https://codesandbox.io/embed/festive-ritchie-5nf31?fontsize=14&hidenavigation=1&theme=dark
这里的问题是 api 将 testItems 作为 class 返回,immer 无法对其进行修改。解决方案是改为发送接口,immer 可以改变。
我在使用 Immer 的产品操纵状态时收到状态突变错误。
当我在同一个 reducer 中手动创建一个测试接口并调用 produce 时,它似乎按预期工作:
export interface ItemSliceState {
items: Array<IItem> | null | undefined;
}
export const initialState: ItemSliceState = { items: [] };
export const updateItem: CaseReducer<
ItemSliceState,
PayloadAction<IItem | null | undefined>
> = (state: ItemSliceState = initialState, action) => {
const testItem: IItem = {
status: 1
};
const testItems: Array<IItems> = [testItem];
const testState: ItemSliceState = { items: testItems };
const nextTestState = produce(testState, draftState => {
if (!draftState || !draftState.items) {
return testState;
}
draftState.items[0].status = 2;
});
const nextState = produce(state, draftState => {
if (!draftState || !draftState.items) {
return state;
}
draftState.items[0].status = 2;
});
...
// testState.items[0].status = 1
// nextTestState.items[0].status = 2
// state.items[0].status = 2
// nextState.items[0].status = 2
为什么'state'被操纵,而同样调用produce时'testState'却保持不变?
状态更新正确的沙盒: https://codesandbox.io/embed/festive-ritchie-5nf31?fontsize=14&hidenavigation=1&theme=dark
这里的问题是 api 将 testItems 作为 class 返回,immer 无法对其进行修改。解决方案是改为发送接口,immer 可以改变。