redux-saga:为什么 `yield call (func, params)` 失败但 `yield call (()=>func(params))` 成功?
redux-saga: why does `yield call (func, params)` fail but `yield call (()=>func(params))` succeed?
这是我的代码,在注释 //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()
returns 表现良好,不是吗?
你应该这样称呼它:
const request = yield call([API, API.get], APIname, APIpath, APIinit)
或
const request = yield call([API, 'get'], APIname, APIpath, APIinit)
这是因为 API
是一个 instance of the class APIClass
。
Javascript调用实例方法时有crazy rules of passing this
。基本上,只有当您直接在代码中编写 API.get()
时,它才会按预期工作。但是,当您通过 call
效果安排调用时,效果对象仅存储 API.get
函数引用,丢失 this
引用。
要使this
正确传递,您应该使用call([context, fn], ...args)
。
这是我的代码,在注释 //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()
returns 表现良好,不是吗?
你应该这样称呼它:
const request = yield call([API, API.get], APIname, APIpath, APIinit)
或
const request = yield call([API, 'get'], APIname, APIpath, APIinit)
这是因为 API
是一个 instance of the class APIClass
。
Javascript调用实例方法时有crazy rules of passing this
。基本上,只有当您直接在代码中编写 API.get()
时,它才会按预期工作。但是,当您通过 call
效果安排调用时,效果对象仅存储 API.get
函数引用,丢失 this
引用。
要使this
正确传递,您应该使用call([context, fn], ...args)
。