根据服务响应更新Redux状态

时间:2020-08-21 13:01:57

标签: reactjs typescript redux redux-thunk immer.js

我已经使用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是connected component)。

dispatch(updateIventoryLocations());

1 个答案:

答案 0 :(得分:2)

Simsons,这是减速器的反模式。 Reducers need to be Pure Functions,并且不应包含异步调用。

此外,减速器需要返回更新状态,但是什么也没有返回。

您可以更新它:

减速器

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

然后使用服务结果调用操作:

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