【问题标题】:Updating redux state based on service response根据服务响应更新 redux 状态
【发布时间】:2020-12-10 20:58:16
【问题描述】:

我已经使用 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());

【问题讨论】:

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


    【解决方案1】:

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

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

    你可以更新它:

    减速器

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

    然后你用服务的结果调用动作:

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

    【讨论】:

    • 如何使用 state.oprationsList 调用 updateService。 UI 无法直接访问状态对象。
    • 为什么您无法访问opratiosList?你能分享你调用调度的组件代码吗?
    • 我的错,看起来我可以访问该列表。调查它。谢谢!
    • 再次感谢 Yash,让我回到了“减速器应该是纯函数”的真相
    • :) 没问题,如果对您有帮助,我将不胜感激
    猜你喜欢
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2021-11-17
    • 2021-12-11
    • 2020-08-19
    相关资源
    最近更新 更多