入门
npm install redux-sagayarn add redux-sagapnpm add redux-sagaimport {useAppDispatch} from "@/hooks";
function App() {
const appDispatch = useAppDispatch()
const buttonHandler = () => {
appDispatch({type: 'increment'})
}
return (
<>
<button onClick={buttonHandler}>increment</button>
</>
)
}
export default App
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});
}
}

最后更新于