入门

npm install 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

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

最后更新于