关于 Thunk 的 Redux 异步操作的问题

Question about Redux async operations with Thunk

我最近才接触到 Redux,并决定学习如何实现它。目前我正在重构我以前的一些学习项目并实现该工具提供的全局状态逻辑。 问题是,我最近偶然发现了用于异步操作的 thunk 中间件,并对可能是一个简单的概念误解但我无法克服的事情感到好奇。
那么,我为什么要分派异步操作?我只是看不到这样做的好处,而不是等待我正在做的任何事情的执行,然后才分派携带我想要的数据的动作。

以简单的获取调用为例,我为什么不执行以下操作:
->等待获取数据
-> 调度获取的数据

而是这样做:
->调度操作
->等待调度操作

可能有一些我不知道的用例,因为对我来说,一个初学者,听起来像是为一些可能不需要的东西添加额外的代码? Idk.
有人可以帮我吗? =)

是的,如您所见,这就是 Dan Abramov 对为什么存在像 thunk 中间件这样的东西的原始解释。

我最近在 Writing Logic with Thunks 上写了一个新的 Redux 文档页面,其中更详细地介绍了 thunk 背后的目的以及如何正确使用它们。我将引用“为什么使用 Thunks?”部分:

Thunks allow us to write additional Redux-related logic separate from a UI layer. This logic can include side effects, such as async requests or generating random values, as well as logic that requires dispatching multiple actions or access to the Redux store state.

Redux reducers must not contain side effects, but real applications require logic that has side effects. Some of that may live inside components, but some may need to live outside the UI layer. Thunks (and other Redux middleware) give us a place to put those side effects.

It's common to have logic directly in components, such as making an async request in a click handler or a useEffect hook and then processing the results. However, it's often necessary to move as much of that logic as possible outside the UI layer. This may be done to improve testability of the logic, to keep the UI layer as thin and "presentational" as possible, or to improve code reuse and sharing.

In a sense, a thunk is a loophole where you can write any code that needs to interact with the Redux store, ahead of time, without needing to know which Redux store will be used. This keeps the logic from being bound to any specific Redux store instance and keeps it reusable.

Redux FAQ entry on "why do we use middleware for side effects?" 链接指向有关此主题的其他信息。