redux-saga:为什么`yield call(func,params)`失败但是`yield call(()=> func(params))`成功了吗?

时间:2019-01-12 19:25:11

标签: aws-api-gateway redux-saga aws-amplify

这是我的代码,在注释//fails的行中失败:

import {API} from "aws-amplify";

function* watchSitesRequested(dispatch) {
  const watchAction = ('SITES_FETCH_REQUESTED');
  const APIname="MyAPIGatewayAPI";
  const APIpath="/configmagic/sites";
  const APIinit={
    headers: {
      'Accept': 'application/json'
    },
    response: true,
  };
  while (true) {
    yield take(watchAction);
    try {
      const request = yield call(API.get, APIname, APIpath, APIinit); //fails
      yield put({type: "SITES_FETCH_SUCCEEDED", payload: {sites: request.data}});
    } catch (e) {
      yield put({type: "SITES_FETCH_FAILED", message: e.message})
    }
  }
}

控制台错误是:

TypeError: Cannot read property '_api' of null
    at API.js:298
    at step (API.js:137)
    at Object.next (API.js:67)
    at API.js:39
    at new Promise (<anonymous>)
    [snip]

但是,如果我按如下所示更改对API.get的调用,它的行为将符合预期:

const request = yield call(() => API.get(APIname, APIpath, APIinit))

为什么?

yield call()我认为应该在函数之后接受多个参数,并且它应该与Promise返回的API.get()一起正常工作,不是吗?

1 个答案:

答案 0 :(得分:2)

您应该这样称呼它:

const request = yield call([API, API.get], APIname, APIpath, APIinit)

const request = yield call([API, 'get'], APIname, APIpath, APIinit)

这是因为APIinstance中的class APIClass

调用实例方法时,Javascript具有crazy rules of passing this。基本上,仅当您直接在代码中编写API.get()时,它才能按预期工作。但是,当您通过call效果放弃呼叫时,效果对象仅存储API.get函数引用,而丢失this引用。

要正确传递this,应使用call([context, fn], ...args)