首页 > 解决方案 > 根据服务响应更新 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());

标签: reactjstypescriptreduxredux-thunkimmer.js

解决方案


Simsons,这是减速器的反模式。Reducers 需要是纯函数,并且不应该包含异步调用。

此外,您的 reducer 需要返回更新后的状态,但没有返回任何内容。

你可以更新它:

减速器

updateIventoryLocations: (state, action) => ({ ...state, locations: action.payload })

您使用服务的结果调用操作:

updateService(state.oprationsList).then((resp) => {
  dispatch(updateIventoryLocations(resp.data));
});

推荐阅读