英文:
Clarification: Why do need async in Redux?
问题
I just can't wrap my head around this. I've seen some examples of performing async operations inside of Redux, for example fetching data with createAsyncThunk. Why can't we just implement fetchPosts() in a regular react component? Is it because of the improved reusability of fetchPosts() function if we used redux? If so, why can't we put that function in a separated/exported module, and import the module whenever we need that function?
我只是不能理解这一点。我已经看到一些在Redux中执行异步操作的示例,例如使用createAsyncThunk获取数据。为什么我们不能只在普通的React组件中实现fetchPosts()呢?是因为如果我们使用Redux,fetchPosts()函数的重用性更好吗?如果是这样,为什么我们不能将该函数放在一个单独的/导出的模块中,并在需要该函数时导入该模块?
英文:
I just can't wrap my head around this. I've seen some examples of performing async operations inside of Redux, for example fetching data with createAsyncThunk. Why can't we just implement fetchPosts() in a regular react component? Is it because of the improved reusability of fetchPosts() function if we used redux? If so, why can't we put that function in a separated/exported module, and import the module whenever we need that function?
答案1
得分: 0
你的问题更与应用程序的结构相关,而不是同步Redux功能。
我认为保持应用程序的不同部分解耦是必要的。
由于您可能需要在其他地方使用fetchPosts()
函数,这就是为什么您希望Redux成为数据的唯一来源。
我相信有人会用更好的话来解释这个问题。
英文:
Your question more related to the structure of the application than the sync Redux function.<br/>
I think it necessary to keep different parts of the application decoupled.
As you may need the fetchPosts()
function somewhere else, that's why you want Redux to be the one source of data.
I am sure people would explain it in some better words.
答案2
得分: 0
Sure, here's the translated content:
"如果可以的话,为什么我们不能将该函数放在一个单独/导出的模块中,并在需要该函数时导入该模块?
这正是 createAsyncThunk
允许你做的事情,它还可以让你轻松处理加载/成功/错误状态。如果你不想使用它,那么你很可能需要为每个新的异步获取情况编写类似的样板代码。
此外,对于特定的数据获取,你可以使用 RTK Query,它将自动为你处理缓存(以及更多)。"
英文:
> If so, why can't we put that function in a separated/exported module, and import the module whenever we need that function?
This is exactly what createAsyncThunk
allows you to do, together with letting you deal easily with loading/success/error states. You don't need to use it if you don't want to, but most likely you will need to write similar boilerplate for each new case of async fetching.
Also, for fetching data specifically, you can use RTK Query instead, which will automatically handle caching (and more) for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论