【问题标题】:How to wait for action and API call to complete using redux saga?如何使用 redux saga 等待操作和 API 调用完成?
【发布时间】:2019-06-01 05:00:03
【问题描述】:

我正在调度一个对后端进行 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 调用调用服务文件。如果这些信息不充分,请告诉我,我会详细说明。

【问题讨论】:

    标签: reactjs redux-saga


    【解决方案1】:

    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* 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 处理请求/错误/成功。那么您将分别需要以下情况GET_USERGET_USER_FAILEDGET_USER_SUCCEEDED

    【讨论】:

      最近更新 更多