简体   繁体   English

Redux-Saga takeEvery 用于多个动作和一个任务

[英]Redux-Saga takeEvery for multiple actions and one task

I have a watcher similar to this我有一个类似于此的观察者

export default function* watch() {
    yield takeEvery(getProducts, fetchData)
    yield takeEvery(getUser, fetchData)
}

But in this form, it does not work, because fetchData must be run once and only if both getProducts and getUser succeeded但是在这种形式下,它不起作用,因为 fetchData 必须运行一次,并且仅当 getProducts 和 getUser 都成功时

Is it possible to somehow transfer both actions to takeEvery, or is there an analogue of takeEvery, which can accept two or more actions and execute the fetchData function only after the successful execution of all the transferred actions?是否有可能以某种方式将两个动作转移到 takeEvery,或者是否有 takeEvery 的类似物,它可以接受两个或多个动作并仅在成功执行所有转移的动作后才执行 fetchData function?

You can use all in combination with take to wait for two actions regardless of order.您可以结合使用alltake来等待两个动作,而不管顺序如何。

export default function* watch() {
    yield all([
        take(getProducts),
        take(getUser)
    ])
    yield call(fetchData)
}

In case you want to wait for these two actions again once the fetching is done you can wrap it a infinite while cycle:如果你想在获取完成后再次等待这两个动作,你可以将它包装成一个无限的 while 循环:

export default function* watch() {
    while (true) {
        yield all([
            take(getProducts),
            take(getUser)
        ])
        yield call(fetchData) 
    }
}

You can also replace the call effect with fork if you don't want to wait for the fetching to be done before waiting for another pair of actions.如果您不想等待抓取完成后再等待另一对操作,也可以将call效果替换为fork

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

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