reactjs - 如何使用 redux 工具包 + redux thunk 创建多个异步操作?
问题描述
这是文档中的示例。我正在寻找使用 redux thunk 实现一个动作,但我希望它保持在与例如updateUser
相同的切片下。users
怎么能用一片来实现呢?
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[fetchUserById.fulfilled]: (state, action) => {
// Add user to the state array
state.entities.push(action.payload)
}
}
})
// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
解决方案
推荐阅读
- c# - 错误 CS0246:找不到类型或命名空间名称“Npgsql”(您是否缺少 using 指令或程序集引用?)
- jquery - 如何最初在 swiper 中隐藏延迟加载的图像
- c++ - P0847 推断这一点 - 它可以允许通用克隆而不需要 CRTP 吗?
- sql - 查询记录但返回按奇数日期范围分组
- reactjs - 如何测试与 Ant Design 的 Popover 内容的交互?
- jquery - 我有一个包含两个捆绑包的网页。Webpack 不会在第二个包上实例化 jquery ui 项
- html - 为什么我的图片在手机 iphone safari 上被拉伸?
- javascript - JQuery 无法理解如何在多个选项中对这些日期进行排序
- go - 以字节为单位读取文件
- amazon-quicksight - 如何根据 Amazon Quicksight 中的子记录对记录进行分组