createAsyncThunk 是一个 Redux Toolkit API,它简化了在 Redux 应用程序中编写异步逻辑的过程。它自动为异步操作的不同状态(pending、fulfilled、rejected)创建和分发 action 类型,并处理通常与编写 thunk 相关的许多样板代码。本页面解释了如何使用 createAsyncThunk 实现 Redux 异步逻辑。
有关 Redux thunk 的一般概念,请参阅 使用 Thunk 编写逻辑。有关使用 RTK Query 进行数据获取的信息,请参阅 RTK Query 基础。
Redux store 和 reducer 在设计上是同步的。当您需要执行像 API 调用这样的异步操作时,您需要可以执行以下操作的中间件:
如果没有专门的工具,这需要为每个操作编写多个 action creator 和 action 类型,以及复杂的 reducer 逻辑来跟踪每个请求的状态。
来源: docs/tutorials/essentials/part-5-async-logic.md155-200
createAsyncThunk 通过生成三种 action 类型并根据 Promise 生命周期自动分发相应的 actions 来抽象这种模式。
来源: docs/tutorials/essentials/part-5-async-logic.md400-460
对于您使用基础类型 'users/fetchUser' 创建的每个异步 thunk,createAsyncThunk 都会自动生成:
pending action: { type: 'users/fetchUser/pending', meta: { requestId, arg } }fulfilled action: { type: 'users/fetchUser/fulfilled', payload: result, meta: { requestId, arg } }rejected action: { type: 'users/fetchUser/rejected', error: error, meta: { requestId, arg } }来源: docs/tutorials/essentials/part-5-async-logic.md395-455
以下是创建和使用异步 thunk 的方法:
来源: docs/tutorials/essentials/part-5-async-logic.md410-426
像任何其他 action creator 一样分发 thunk
来源: docs/tutorials/essentials/part-5-async-logic.md530-558
为了有效使用异步 thunk,您的状态应该跟踪请求的状态
在 slice 中使用 extraReducers 来处理 thunk 的生命周期 actions
来源: docs/tutorials/essentials/part-5-async-logic.md480-520
通过 action creator 向您的 thunk 传递参数
来源: docs/tutorials/essentials/part-5-async-logic.md167-175
condition 选项可防止不必要的 API 调用
来源: docs/tutorials/essentials/part-5-async-logic.md602-625
您可以使用 AbortController 取消进行中的请求
来源: docs/tutorials/essentials/part-6-performance-normalization.md410-425
Redux Toolkit 为异步 thunk 提供了出色的 TypeScript 支持
为了更好地集成 TypeScript,请创建 createAsyncThunk 的预类型版本
来源: docs/tutorials/essentials/part-5-async-logic.md270-280 docs/usage/UsageWithTypescript.md260-280
使用标准化方法跟踪请求状态
来源: docs/tutorials/essentials/part-5-async-logic.md295-315
使用 RTK Query 或手动缓存管理时,请使用基于标签的方法来控制何时重新获取数据
来源: docs/tutorials/essentials/part-8-rtk-query-advanced.md160-215
在 rejected 情况下一致地处理错误
来源: docs/tutorials/essentials/part-5-async-logic.md500-520
在组件挂载时,在 useEffect 中分发 thunk 以加载数据
来源: docs/tutorials/essentials/part-5-async-logic.md550-558
使用请求状态来渲染适当的 UI
createAsyncThunk 为处理 Redux 应用程序中的异步操作提供了强大的抽象。它:
createSlice)无缝协作通过使用 createAsyncThunk,您可以显著减少处理异步操作所需的样板代码量,同时保持清晰一致的异步状态管理模式。
来源: docs/tutorials/essentials/part-5-async-logic.md10-40 docs/introduction/why-rtk-is-redux-today.md10-30
刷新此 Wiki
最后索引时间2025 年 4 月 18 日 (304031)