reactjs - 根据服务响应更新 redux 状态
问题描述
我使用 createSlice 创建了一个动作和减速器。
在其中一个操作中,我使用来自状态的集合来调用服务。我想根据服务的响应更新状态数据。
成功时我想更新state.locations
,失败时我想更新state.errorData
.
const ManageInventoriesState = createSlice({
name: "ManageInventoriesReducer",
initialState,
reducers: {
updateIventoryLocations: (state) => {
updateService(state.oprationsList).then((resp) => {
state.locations = resp.data;
}).catch((err) => {
state.errorData = err.data;
});
},
},
});
但是当我尝试这样做时,我收到以下错误,
无法在已撤销的代理上执行“设置”。
如何正确地做到这一点。
从 UI 我只是调度动作(UI 是一个连接的组件)。
dispatch(updateIventoryLocations());
解决方案
Simsons,这是减速器的反模式。Reducers 需要是纯函数,并且不应该包含异步调用。
此外,您的 reducer 需要返回更新后的状态,但没有返回任何内容。
你可以更新它:
减速器
updateIventoryLocations: (state, action) => ({ ...state, locations: action.payload })
您使用服务的结果调用操作:
updateService(state.oprationsList).then((resp) => {
dispatch(updateIventoryLocations(resp.data));
});
推荐阅读
- regex - IIS 使用正则表达式重写规则
- json - 无法将“字符串”类型的值转换为预期的参数类型“数据”
- macros - 使用基于枚举名称的宏创建方法
- mongodb - 如何将 mongodb(安装在 ec2 上)连接到 Robomongo?
- c# - 为了将对象的实例传递给“GC.AddMemoryPressure”方法,使用了哪些 C# 语言机制?
- java - 除了在forloop内部之外,有没有任何有效的方法来调用对象列表的查询
- google-sheets - 如何使用 ARRAYFORMULA 执行累积和计算
- google-cloud-run - 如何在无需添加授权令牌的情况下调用 Cloud Run 应用
- javascript - 为什么将函数导入另一个文件时函数的属性不可见?
- matlab - 如何将字符串'pi'转换为double?(MATLAB 2015a)