为什么要使用 redux saga 或 thunk

why to use redux saga or thunk at all

我真的被redux saga弄糊涂了。因此,无论我看什么文章,他们都解释说它是为了解决 redux 和异步调用的副作用,甚至他们对 saga 和 thunk 的区别进行了解释,但所有这些都令人困惑。 他们根本没有解释为什么我应该使用传奇?如果我让异步调用等待它然后更新 redux 状态有什么问题。

我需要的是一个简单明了的解释,说明为什么以及在什么情况下我们需要使用 redux saga 或 thunk?

如果我不使用 saga,那么如果我点击 1000 次,我的代码将 运行 异步代码并等待结果 1000 次,我说得对吗,但是有了 saga,我有办法控制它运行 全部并行(分叉)还是 运行 最后一个?

so for whatever action that needs to change the redux store (not the component state) and is asynchronous we better to use thunk or saga but we do not have to and if not using it still it is valid. right?

首先,redux-saga 或 redux-thunk 是建立在 Redux's middleware 之上的库,用于处理与 redux 主要数据流无关的问题,例如API 呼叫、日志记录、路由。您显然可以编写自己的中间件来处理异步流,而不是使用那些库,这可能会大大减轻您的应用程序大小。然而,redux-thunk 尤其是 redux-saga 有很多语法糖 APIs 来处理异步流的复杂使用,比如 racing, sequencing API calls, canceling API call based on condition 等等,减少了很多自己实现等价逻辑的工作。

Also when we say redux is syncronous flow by nature still we can swait for the call and then proceed. So how is that different from saga or thunk?

这更多是个人意见,但我认为使用这些库的主要原因是关注点分离。通过中间件实现来处理所有异步流,我们可以在 react/redux 应用程序中有 3 个逻辑部分:redux 部分由用于同步数据流的纯函数组成,redux 中间件部分(可以是 redux-thunk 或 redux-saga)它处理来自 redux 的所有 API 调用和副作用,并反应部分处理用户交互和与 redux 存储的通信。这样代码将更易于管理,也更容易进行单元测试。

Am I right to say if I do not use saga then if I click 1000 times my code will rin the asnc code and wait for result 1000 times but with saga I have a way to control over it either run all in parallel(fork) or just run the last one?

同样,可以使用自行实现的 redux 中间件来限制除最后一次调用之外的所有调用。然而,redux-saga 已经有 an API for this case,还有更多其他常见的异步问题。