Redux Toolkit 简化了 React 应用程序中的全局状态管理。在本文中,我们将探讨如何使用 Redux Toolkit 实现身份验证系统,包括存储配置、切片和带有 thunk 的异步操作。
1。配置 Redux 存储
Redux 存储是使用configureStore 配置的。在app.tsx中,我们设置了全局reducer、中间件,并启用了用于调试的开发工具。
import { lazy } from 'react'; import { createRoot } from 'react-dom/client'; import { Provider } from "react-redux"; import { combineReducers, configureStore } from '@reduxjs/toolkit'; import { rootReducer } from './slice'; import { setupAxios } from './_metronic/helpers/Axios'; import axios from 'axios'; import { thunk } from 'redux-thunk'; setupAxios(axios); const AppRoutes = lazy(() => import('./routers/AppRoutes')); const store = configureStore({ reducer: combineReducers({ masterState: rootReducer, }), middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(thunk), devTools: true, }); createRoot(document.getElementById('root')!).render( <Provider store={store}> <AppRoutes /> </Provider> );
2。创建根减速器
根减速器通过组合不同的切片来管理全局状态。在这里,我们包含一个用于身份验证的 auth 切片。
import { AuthReducer } from "#/modules/auth/store/auth.slice"; import { combineReducers } from "redux"; export const rootReducer = combineReducers({ Auth: AuthReducer, });
Authslice 处理特定于身份验证的状态,该状态是使用 createSlice 定义的。
3。定义身份验证切片
使用 createSlice,我们定义状态结构、同步化简器和 extraReducers 来处理异步操作。
import { createSlice } from "@reduxjs/toolkit"; import { AuthState, initialAuthState } from "../model/authModel"; import { setLocalStorageData } from "#/_metronic/helpers/localstorage/accessToken"; import { AUTH_KEY, REFRESH_KEY } from "#/_metronic/helpers/env"; import { login } from "./auth.asyncAction"; const initialState: AuthState = initialAuthState; export const authSlice = createSlice({ name: "auth", initialState, reducers: {}, extraReducers: (builder) => { builder .addCase(login.pending, (state) => { state.loading = true; state.error = undefined; state.isSubmitting = true; }) .addCase(login.fulfilled, (state, action) => { const { payload }: any = action; if (payload?.status === 'Error') { state.error = payload?.message || payload; } else { state.success = true; state.isLogin = true; setLocalStorageData(AUTH_KEY, payload?.api_token); setLocalStorageData(REFRESH_KEY, payload?.refreshToken); } state.loading = false; state.isSubmitting = false; }) .addCase(login.rejected, (state, action) => { const { payload }: any = action; state.loading = false; state.error = payload?.data || payload; state.isSubmitting = false; }); }, }); export const { reducer: AuthReducer } = authSlice;
4。使用 createAsyncThunk 创建异步操作
登录异步操作与 API 交互以处理用户身份验证。
import { createAsyncThunk } from "@reduxjs/toolkit"; import { doLogin } from "../api/auth_api"; export const login = createAsyncThunk('login', async (payload: any, { rejectWithValue }) => { try { return await doLogin(payload); } catch (error: any) { return rejectWithValue(error?.data || error); } });
该操作调用 API 并使用rejectWithValue 处理响应或错误。
5。创建身份验证 API
API层使用axios与后端进行通信。这是登录请求的实现。
import axios from 'axios'; import { ILogin, UserModel } from '../model/authModel'; import { BASE_URL } from '#/_metronic/helpers/env'; export const AUTH_URL = `${BASE_URL}/auth`; export const doLogin = (payload: ILogin) => axios.post<UserModel>(AUTH_URL, payload);
使用 Redux Toolkit,管理全局状态变得简化,特别是在处理用户身份验证等复杂工作流程时。通过将实现分解为更小的模块(存储、切片和 API),我们确保了 React 应用程序的可扩展性和可维护性。
以上是状态管理:Redux 工具包 React JS的详细内容。更多信息请关注PHP中文网其他相关文章!