当我在弹出窗口中注销时,当我单击它并退出会话时,会出现确认信息,这很好,问题是当我再次注册或登录时,(isLogouting 和 isOpeLogoutDialogue)不会更改为 false。我提供了有关 redux 工具包的所有配置代码
import { createSlice } from "@reduxjs/toolkit";
import GlobalReducer from "./GlobalReducer";
import GlobalStates from "./GlobalStates";
const GlobalSlice = createSlice({
name: "global",
initialState: GlobalStates,
reducers: GlobalReducer,
});
export default GlobalSlice.reducer;
export const {
handleOpenLogoutDialogue,
handleCloseLogoutDialogue,
handleLoggedOut,
} = GlobalSlice.actions;
const GlobalStates = {
isOpeLogoutDialogue: false,
isLogOuting: false,
};
export default GlobalStates;
import { router } from "@inertiajs/react";
const GlobalReducer = {
handleLoggedOut(state, action, dispatch) {
state.isLogOuting = true;
router.post(route("logout"), {
onFinish: () => {
state.isLogOuting = false;
state.isOpeLogoutDialogue = false;
},
});
},
handleOpenLogoutDialogue(state, action) {
state.isOpeLogoutDialogue = true;
},
handleCloseLogoutDialogue(state, action) {
state.isOpeLogoutDialogue = false;
},
};
export default GlobalReducer;
import { configureStore } from "@reduxjs/toolkit";
import AuthReducer from "./Slices/Auth/AuthSlice";
import GlobalReducer from "./Slices/Global/GlobalSlice";
const store = configureStore({
reducer: {
auth: AuthReducer,
global: GlobalReducer,
}
});
export default store;
Reducer 是纯函数,它们无法调用
router.post
并尝试应用任何异步逻辑。 onFinish
应向存储分派操作以实现任何状态更改。
我建议将此逻辑重构为异步操作,该操作可以(a)应用异步逻辑和(b)通过生成的挂起/已完成/拒绝操作将操作分派回存储,以便您在额外的减速器中处理。
基本示例:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import GlobalReducer from "./GlobalReducer";
import GlobalStates from "./GlobalStates";
export const handleLoggedOut = createAsyncThunk(
"auth/handleLogout",
async (_, thunkApi) => {
return new Promise((resolve => {
router.post(route("logout"), {
onFinish: resolve,
});
}))
}
);
const GlobalSlice = createSlice({
name: "global",
initialState: GlobalStates,
reducers: GlobalReducer,
extraReducers: builder => {
builder
.addCase(handleLoggedOut.pending, () => {
state.isLogOuting = true;
})
.addCase(handleLoggedOut.fulfilled, () => {
state.isLogOuting = false;
state.isOpeLogoutDialogue = false;
})
.addCase(handleLoggedOut.rejected, () => {
state.isLogOuting = false;
state.isOpeLogoutDialogue = false;
});
},
});
export const {
handleOpenLogoutDialogue,
handleCloseLogoutDialogue,
} = GlobalSlice.actions;
export default GlobalSlice.reducer;