入门
假设我们有一个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
现在我们点击按钮,就可以在网络请求面板中,看到发送出了一条请求。
最后更新于
这有帮助吗?