我来自于redux-thunk的用法,并且了解中间件的概念,我们曾经使用过中间件的概念来获取api响应并将其附加到带有分派动作的存储中。我知道该函数在yield
处停止,仅通过.next
再次获得触发器。有人可以在下面的情况下进行解释
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}
/*
Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
Allows concurrent fetches of user.
*/
function* mySaga() {
yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}
/*
Alternatively you may use takeLatest.
Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
dispatched while a fetch is already pending, that pending fetch is cancelled
and only the latest one will be run.
*/
function* mySaga() {
yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}
export default mySaga;
在yield put
之后没有下一个调用yield call
的情况
答案 0 :(得分:1)
Redux sagas像协程一样工作。也就是说,您不负责遍历saga迭代器。传奇库为您完成了此任务。
创建传奇英雄中间件并将其赋予根传奇后:
sagaMiddleware.run(rootSaga)
saga库在内部创建rootSaga生成器的迭代器,并根据其内部逻辑调用next。这样便可以读取和处理您在Sagas中产生的效果。
除非您正在编写测试并模拟redux-saga行为,否则在使用redux-saga时您永远不会打电话给自己。