You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux State无法正确接收MySQL后端数据问题求助

问题排查:Redux State无法存储异步获取的后端数据

你的核心问题出在Slice代码的结构错误:extraReducers被错误嵌套在了reducers对象内部,导致Redux无法识别异步action的状态更新逻辑,所以即便请求成功,状态也不会被更新。

错误位置分析

在createSlice的配置中,reducers(处理同步action)和extraReducers(处理异步action或外部action)是同级的顶层属性,你现在把extraReducers写进了reducers里,这部分代码完全不会被执行,自然无法更新supplierInfo。

修正后的Slice代码

export const SupplierSlice = createSlice({
  name: "supplier",
  initialState,
  reducers: {
    addSupplier: (state, action) => {
      state.supplierInfo.push(action.payload);
    },
  },
  // extraReducers移到顶层,和reducers同级
  extraReducers: (builder) => {
    builder.addCase(fetchSuppliers.pending, (state) => {
      state.loading = true;
    });
    builder.addCase(fetchSuppliers.fulfilled, (state, action) => {
      state.loading = false;
      state.supplierInfo = action.payload;
      state.error = "";
    });
    builder.addCase(fetchSuppliers.rejected, (state, action) => {
      state.loading = false;
      state.supplierInfo = [];
      state.error = action.error.message;
    });
  },
});
export default SupplierSlice.reducer;
export const { addSupplier } = SupplierSlice.actions;

验证点

  1. 修正后,Redux DevTools的State标签页会显示supplierInfo被正确赋值为后端返回的数据
  2. 组件中useSelector获取的suppliers会输出正确内容

内容的提问来源于stack exchange,提问作者Jap YG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 01:22:38