redux saga如何在函数中触发next with

How does redux saga trigger next with in a function

我来自 redux-thunk 的使用,并且了解中间件的概念,我们曾经在其中获取 api 响应并将其附加到 store with dispatch actions.In redux-thunk 代码如下格式并且对生成器函数知之甚少,我知道函数在 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 call之后没有next

如何调用yield put

Redux sagas 像协程一样工作。也就是说,您不负责迭代 saga 迭代器。 saga 图书馆为您做这件事。

当你创建你的传奇中间件并给它你的根传奇时:

sagaMiddleware.run(rootSaga)

saga库在内部创建rootSaga生成器的迭代器,并根据其内部逻辑调用next。这就是它能够读取和处理您在 sagas 中产生的效果的方式。

除非你正在编写测试和模拟 redux-saga 行为,否则在使用 redux-saga 时你永远不会自己调用 next。