如何使用createSlice重置Redux状态?

e5nqia27  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(126)

我尝试在用户注销时为用户重置Redux状态,以下是我的代码:

export interface UserInterface {
    id: string | null;
    name: string | null;
    email: string | null;
    notes: Array<string>
    seq: number | null
}

export interface UserState {
    user: UserInterface
}

const initialState: UserState = {
    user: {
        id: null,
        name: null,
        email: null,
        notes: [],
        seq: null,
    },
}

export const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {
        setUser: (state, action: PayloadAction<UserInterface>) => {
            state.user = action.payload
        },
        removeUser: (state) => {
            state.user = {
                id: null,
                name: null,
                email: null,
                notes: [],
                seq: null,
            }
        },
    }
});

我想执行removeUser reducer而不使用任何排序或参数,因为我只是在用户注销时重置状态。dispatch(removeUser())这是否正确?

e1xvtsh3

e1xvtsh31#

是的,这是正确的用法。另外,您可以重写操作removeUser like

removeUser: (state) => {
  return initialState
}

相关问题