Redux状态未从后端正确接收数据(mySQL)

crcmnpdw  于 2023-08-05  发布在  Mysql
关注(0)|答案(1)|浏览(99)

我在将数据从后端(mySQL)渲染到前端时遇到了问题。我已经在redux devtools和console日志中进行了调试,但我仍然找不到原因。数据在控制台日志中正确获取,但当我记录状态时,它只是空的。在redux devtools中,我可以看到action选项卡中的数据,状态从pending变为fulfilled。然而,当它被实现时,状态只是空的。
这是我的slice组件的初始状态:

const initialState = {
  loading: false,
  error: "",
  supplierInfo: [
    {
      id: "",
      supplierName: "",
      supplierTin: "",
      supplierAddress: "",
      telNumber: "",
      celNumber: "",
      emailAddress: "",
    },
  ],
};

字符串
这是我的fetch函数(数据被正确记录):

export const fetchSuppliers = createAsyncThunk(
  "/supplier/fetchSuppliers",
  async () => {
    try {
      const response = await axios.get("http://localhost:3000/api/get");

      return response.data;
    } catch (error) {
      throw error;
    }
  }
);


这是我的slice代码:

export const SupplierSlice = createSlice({
  name: "supplier",
  initialState,
  reducers: {
    addSupplier: (state, action) => {
      state.supplierInfo.push(action.payload);
    },
    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;


发送数据的代码:

export const SuppliersTable = () => {
  const suppliers = useSelector((state) => state.supplier.supplierInfo);
  console.log(suppliers);
  const data = suppliers;
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchSuppliers());
  }, [dispatch]);


上面的console.log是空的。我不知道为什么。也许问题出在减速器上?我可以看到数据在行动选项卡虽然,但它不是显示到状态。
这是来自redux devtools中的action选项卡:enter image description here
这是来自状态选项卡:enter image description here
正如您所看到的,没有任何内容显示到状态中。我不知道为什么。有人能帮帮忙吗谢谢你!
我已经调试了几个小时了。使用日志语句,redux devtools。我看到数据从后端,但它不是在国家。

cig3rfwq

cig3rfwq1#

Redux状态未接收数据,因为您的slice格式代码错误。

请将我的示例代码与您的真实的代码进行比较。请检查您的供应商切片代码是看起来错误。extraReducer不应在减速器的块内。如果你把它移出减速器,它就会工作。

const supplierSlice = createSlice({
  name: "supplier",
  initialState: initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchSuppliers.pending, (state, action) => {
      console.log(action);
      state.loading = true;
    });
    builder.addCase(fetchSuppliers.fulfilled, (state, action) => {
      state.supplierInfo = action.payload;
      state.loading = false;
    });
    builder.addCase(fetchSuppliers.rejected, (state, action) => {
      state.loading = false;
    });
  }
});

字符串
下面是示例example

相关问题