gpt4 book ai didi

Redux 传奇 : difference between yield array to fork in the root saga

转载 作者:行者123 更新时间:2023-12-01 13:17:07 25 4
gpt4 key购买 nike

传奇新手,我在我的根传奇中使用它:

function* rootSaga() {
yield [
cycleRoot(), // fetches root
cycleChain(), // fetch chain
cycleChatBadge(), // fetches badge
watchNotifications(), // navigate on ROOT_DONE
watchNavigation(), // listen to navigation changes
watchAppState(), // background/foreground
watchConnection(), // connection chages
];
}

有用。但是我已经看到使用以下示例:
function* rootSaga() {
yield fork (cycleRoot);
yield fork (cycleChain);
...
}

点燃根传奇时,这两者之间有什么区别吗?

最佳答案

这里实际上有两个不同之处。

1. 使用效果 vs 直接调用传奇。

redux-saga 库可以直接处理 yielding 生成器,但是这种方法使得在编写测试时很难使用模拟。相反,您可以使用 call影响。此代码将与您的第一个代码段完全相同,只是它是使用 call 声明式编写的。影响。 (另外,我在这里使用了 all 效果,因为生成数组已被弃用)。

function* rootSaga() {
yield all([
call(cycleRoot),
call(cycleChain),
...
]);
}

要获得更深入的见解(包括测试示例),我建议阅读 redux-saga 文档的这一部分: https://redux-saga.js.org/docs/basics/DeclarativeEffects.html

您可以使用 call调用函数和传奇的效果。但是,如果您对编写测试不感兴趣并且确定您永远不会,我发现使用 call 很有用。区分调用传奇(使用 call )和常规函数(直接调用)的效果。

2. 使用 fork而不是 call

第二个区别是,在您的第一个代码段中,您会阻止 rootSaga 执行,直到所有的 saga 完成。要使它们非阻塞,您可以使用 fork影响。
function* rootSaga() {
yield all([
call(cycleRoot),
call(cycleChain),
...
]);
console.log('This happens only after all sagas are finished (including fetching etc.')
}

function* rootSaga() {
yield all([
fork(cycleRoot),
fork(cycleChain),
...
]);
console.log('This happens immediately after the sagas are executed - it does not wait for async action like fetching')
}

您可以再次阅读文档中的非阻塞调用: https://redux-saga.js.org/docs/advanced/NonBlockingCalls.html

总结 我建议在调用其他传奇时总是使用效果(如 call/ fork )并使用 fork除非有充分的理由阻止它,否则会影响在 root saga 中启动其他 saga。

关于Redux 传奇 : difference between yield array to fork in the root saga,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53798546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com