简体   繁体   English

Redux-Saga连接多个发电机进行存储

[英]Redux-Saga connect multiple generators to store

This may be fairly basic but I haven't found an solution. 这可能是相当基本的,但我还没有找到解决方案。 I'm using redux-saga to handle my async API calls with redux. 我正在使用redux-saga来处理我的redux异步API调用。 I need to connect multiple listeners to the store. 我需要将多个侦听器连接到商店。 I tried fork like in the examples, and the first fork works, but the second one doesn't. 我在示例中尝试了fork ,第一个fork工作,但第二个没有。 How can I connect multiple listeners? 如何连接多个侦听器?

export default function* mySaga() {
  yield [
    fork(yield* takeEvery("FRIEND_FETCH_REQUESTED", fetchFriends)), // works
    fork(yield* takeEvery("CREATE_USER_REQUESTED", createUser)),    // doesn't work
  ]
}

Thanks! 谢谢!

This is because fork takes a function that returns a promise or a generator function as per the documentation here: 这是因为fork根据以下文档获取了一个返回promisegenerator函数的函数

http://yelouafi.github.io/redux-saga/docs/api/index.html#forkfn-args http://yelouafi.github.io/redux-saga/docs/api/index.html#forkfn-args

To make your situation work, just put the yield* in a generator function and it should all work : 为了使你的情况工作,只需将yield*放在生成器函数中,它应该全部工作:

export default function* mySaga() {
  yield [
    fork(watchFetchFriends),
    fork(watchCreateUser)
  ]
}
function watchFetchFriends() {
   yield* takeEvery("FRIEND_FETCH_REQUESTED", fetchFriends);
}
function watchCreateUser() {
    yield* takeEvery("CREATE_USER_REQUESTED", createUser);
}

Btw, I am not sure how your first yield* works though. 顺便说一句,我不确定你的第一次yield*是如何起作用的。

Got same problem, I found another way 遇到同样的问题,我发现了另一种方式

export default function* root(){
    yield [
        takeEvery("FRIEND_FETCH_REQUESTED", fetchFriends),
        takeEvery("CREATE_USER_REQUESTED", createUser)
    ];
}

Redux Saga uses the all function in the recent version (0.15.3) to combine multiple sagas to one root saga for the Redux store. Redux Saga使用最新版本(0.15.3)中的all函数将多个sagas组合到Redux商店的一个根传奇。

import { takeEvery, all } from 'redux-saga/effects';

...

function *watchAll() {
  yield all([
    takeEvery("FRIEND_FETCH_REQUESTED", fetchFriends),
    takeEvery("CREATE_USER_REQUESTED", createUser)
  ]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM