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中文網其他相關文章!