前端
PythonJava运维数据库
状态管理
状态管理
  • 🖥️Redux Tookit
    • Introduction
      • 介绍
    • Tutorials
      • 🖥️快速开始
      • 🏐在TypeScript环境使用
    • Using Redux toolkit
      • 使用Immer编写Reducers
      • 性能与数据范式化
      • 异步逻辑与数据请求
      • Usage With TypeScript
    • API Refrence
      • Store Setup
        • configureStore
        • getDefaultMiddleware
        • Immutability Middleware
        • Serializability Middleware
        • Action Creator Middleware
        • createListenerMiddleware
        • createDynamicMiddleware
        • getDefaultEnhancers
        • autoBatchEnhancer
      • Reducer and Actions
        • createReducer
        • createAction
        • createSlice
        • createAsyncThunk
        • createEntityAdapter
        • combineSlices
      • Other
        • createSelector
        • Matching Utilities
    • RTX Query
      • RTK Query Overview
      • Comparson with Other Tools
      • Examples
      • Usage With TypeScript
      • Using RTK Query
        • Queries
        • Mutations
      • API Refrence
        • createApi
        • fetchBaseQuery
        • ApiProvider
        • setupListeners
        • Generated API Slices
          • Generated API Slices
          • Redux Integration
          • Endpoints
          • Code Splitting
          • Utilities
          • React Hooks
  • 🚚Redux-Saga
    • 入门
    • 基础概念
    • API
    • 技巧
  • 🚑React Redux
    • 安装
    • 教程
    • 使用 React Redux
    • API 参考
  • 🚕生态
    • Redux Persist
    • zustand
      • 使用 useShallow 防止重新渲染
由 GitBook 提供支持
在本页

这有帮助吗?

  1. Redux-Saga

入门

npm install redux-saga
yarn add redux-saga
pnpm add redux-saga

假设我们有一个UI,可以通过单击按钮从远程服务器获取一些用户数据:

import {useAppDispatch} from "@/hooks";

function App() {
    const appDispatch = useAppDispatch()
    const buttonHandler = () => {
        appDispatch({type: 'increment'})
    }
    return (
        <>
            <button onClick={buttonHandler}>increment</button>
        </>
    )
}

export default App

组件向Store派发一个普通的Object操作。我们将创建一个Saga来监视所有USER_FETCH_REQUESTED操作,并触法API调用来从远程服务器获取用户数据。

import {takeEvery, call, put} from "redux-saga/effects";

function* rootSaga() {
    yield takeEvery("USER_FETCH_REQUESTED", fetchUser)
}


export default rootSaga;

const fetchUserById = async (userId: number) => {
    return await fetch(`/api/users/${userId}`)
        .then(response => response.json())
}

function* fetchUser(action: Record<string, any>) {
    try {
        const user: Record<string, any> = yield call(fetchUserById, action.payload);
        yield put({type: "USER_FETCH_SUCCEEDED", user: user});
    } catch (e: any) {
        yield put({type: "USER_FETCH_FAILED", message: e.message});
    }
}

要运行 Saga,我们必须使用redux-saga中间件将其连接到 Redux Store。

import {configureStore, type Middleware} from "@reduxjs/toolkit";
import createSagaMiddleware from "redux-saga";
import logger from 'redux-logger'
import userReducer from "@/store/userSlice";
import rootSaga from "@/store/rootSaga.ts";

const sagaMiddleware = createSagaMiddleware()
const store = configureStore({
    reducer: {
        user: userReducer
    },
    devTools: import.meta.env.MODE !== 'production',
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(sagaMiddleware, logger as Middleware)
})

sagaMiddleware.run(rootSaga)

export default store

现在我们点击按钮,就可以在网络请求面板中,看到发送出了一条请求。

上一页React Hooks下一页基础概念

最后更新于9个月前

这有帮助吗?

🚚