Redux 狀態無法正確存取後端 (mySQL) 數據
P粉139351297
P粉139351297 2023-09-20 10:40:44
0
1
536

我在後端(mySQL)和前端之間渲染資料時遇到了問題。我已經在redux devtools和控制台日誌中進行了調試,但仍然找不到原因。數據在控制台日誌中正確獲取,但當我記錄我的狀態時,它只是空的。在redux devtools中,我可以在操作標籤中看到數據,並且狀態從待定變為已完成。然而,當它完成時,狀態就是空的。

這是我的切片組件的初始狀態:

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

這是我的獲取函數(資料被正確記錄):

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;
    }
  }
);

這是我的切片程式碼:

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只是空的。我不知道為什麼。也許問題在reducers?儘管我可以在操作標籤中看到數據,但它沒有顯示到狀態中。

這是redux devtools中的操作選項卡:

在此輸入影像描述

這是狀態標籤中的內容:

在此輸入影像描述

如您所見,狀態中沒有顯示任何內容。我不知道為什麼。有人可以幫忙嗎?謝謝!

我已經嘗試了幾個小時的調試。使用日誌語句,redux devtools。我從後端看到了數據,但它沒有在狀態中。

P粉139351297
P粉139351297

全部回覆(1)
P粉550323338
Redux狀態未接收到數據,因為您的程式碼語法有誤。

請將我的範例程式碼與您的實際程式碼進行比較。

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;
    });
  }
});

這是範例範例

#
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!