如何使用 redux saga 等待操作和 API 调用完成?
How to wait for action and API call to complete using redux saga?
我正在调度一个对后端进行 API 调用的操作,然后我正在更新商店。在我的 React 组件中的动作分派之后,我需要在下一行访问道具。
this.props.getUser();
//need the user here
console.log(this.props);
Action 在我的 actions.js 文件中看起来像这样,并且正在映射到我的 React 组件中的 props
const getUser = () => ({
type: 'GET_USER'
});
该操作进入 Saga.js 文件,该文件通过 API 调用调用服务文件。如果这还不够,请告诉我,我会详细说明。
在redux-saga
中,yield
是等待API调用完成的关键字,returns我们的结果。将它用于 API 调用的基本模式如下所示:
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...' <-- the path to your API endpoint
// will be fired on GET_USER actions
function* getUser(action) {
try {
// redux-saga will wait till the endpoint function will finish and return
const user = yield call(Api.getUser);
// In your reducer: you're returning the user
yield put({type: "GET_USER_SUCCEEDED", user: user});
} catch (e) {
// Or an error message
yield put({type: "GET_USER_FAILED", message: e.message});
}
}
// the saga you link to your middle-ware setup where you setting up the store.
function* rootSaga() {
yield takeEvery("GET_USER", getUser);
}
请注意,您需要 redux
来处理 request/error/success。那么您将分别需要以下案例 GET_USER
、GET_USER_FAILED
和 GET_USER_SUCCEEDED
。
我正在调度一个对后端进行 API 调用的操作,然后我正在更新商店。在我的 React 组件中的动作分派之后,我需要在下一行访问道具。
this.props.getUser();
//need the user here
console.log(this.props);
Action 在我的 actions.js 文件中看起来像这样,并且正在映射到我的 React 组件中的 props
const getUser = () => ({
type: 'GET_USER'
});
该操作进入 Saga.js 文件,该文件通过 API 调用调用服务文件。如果这还不够,请告诉我,我会详细说明。
在redux-saga
中,yield
是等待API调用完成的关键字,returns我们的结果。将它用于 API 调用的基本模式如下所示:
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...' <-- the path to your API endpoint
// will be fired on GET_USER actions
function* getUser(action) {
try {
// redux-saga will wait till the endpoint function will finish and return
const user = yield call(Api.getUser);
// In your reducer: you're returning the user
yield put({type: "GET_USER_SUCCEEDED", user: user});
} catch (e) {
// Or an error message
yield put({type: "GET_USER_FAILED", message: e.message});
}
}
// the saga you link to your middle-ware setup where you setting up the store.
function* rootSaga() {
yield takeEvery("GET_USER", getUser);
}
请注意,您需要 redux
来处理 request/error/success。那么您将分别需要以下案例 GET_USER
、GET_USER_FAILED
和 GET_USER_SUCCEEDED
。