使用 Immer 的产品来操纵状态时,我收到了状态突变错误。
当我在同一个减速器中手动创建测试接口并调用生产时,它似乎按预期工作:
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
为什么“状态”被操纵,而“testState”在以相同方式调用生产时保持不变?
正确更新状态的沙箱: https ://codesandbox.io/embed/festive-ritchie-5nf31?fontsize=14&hidenavigation=1&theme=dark