如何使用redux saga等待操作和API调用完成?

时间:2019-06-01 05:00:03

标签: reactjs redux-saga

我正在调度一个操作,该操作向后端进行API调用,然后更新商店。我需要在React组件中的动作分派之后在下一行访问props。

this.props.getUser();

//need the user here
console.log(this.props);

动作在我的actions.js文件中看起来像这样,并被映射到我的react组件中的道具

const getUser = () => ({
  type: 'GET_USER'
});

操作进入Saga.js文件,该文件使用API​​调用来调用服务文件。如果没有足够的信息,请告诉我,我将对此进行详细说明。

1 个答案:

答案 0 :(得分:0)

redux-saga中,yield是等待API调用完成并返回结果的关键字。将其用于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* gethUser(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});
   }
}

// this is the saga you link to your middle-ware setup where you setting up the store.
function* rootSaga() {
  yield takeEvery("GET_USER", getUser);
}

请注意,您将希望redux处理请求/错误/成功。那么您将分别需要以下情况GET_USERGET_USER_FAILEDGET_USER_SUCCEEDED

相关问题