【发布时间】:2021-11-21 02:34:47
【问题描述】:
我正在构建一个简单的应用程序。我正在使用 redux 工具包进行状态管理
它必须查询数据库以检查用户是否经过身份验证。
如果是,它会为用户设置名称、电子邮件等
当它检查数据库时,我想在前端加载一个微调器,微调器占据整个屏幕,并在数据库查询时随时显示。出于这个原因,我想要一个单独的应用程序状态,它有两个值,即加载和错误
应用切片
const initialState = {loading : false,error:false,error_msg:null}
export const appSlice = createSlice({
name : 'app',
initialState : {value : initialState},
reducers : {
toggle : (state,action)=>{
state.value.loading = action.payload
}
},
});
用户切片
const initialState = { name: "", email: "", role: "", isAuthenticated: false };
export const authenticateUser = createAsyncThunk(
"user/authenticate",
async () => {
let res = await axiosInstance.get("/user/authenticate");
return res.data;
}
);
export const userSlice = createSlice({
name: "user",
initialState: { value: initialState },
reducers: {},
extraReducers: (builder) => {
builder.addCase(authenticateUser.pending, (state, action) => {
//change loading to true for app slice something like (state.app.loading = true)
});
builder.addCase(authenticateUser.fulfilled, (state, action) => {
state.value = action.payload
});
builder.addCase(authenticateUser.rejected, (state, action) => {
//change error to true for app slice something like (state.app.error = true)
//change error_msg to action.payload for app slice
//something like (state.app.error_msg = action.payload)
});
},
});
【问题讨论】:
标签: reactjs redux react-redux mern redux-toolkit