axios React useState在声明后不执行代码

pgvzfuti  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(135)

我正在做一个React项目,遇到了一个关于useState钩子的奇怪问题。具体来说,我有一个名为useAxios的自定义钩子,它使用useState来管理状态。但是,放在useState声明之后的任何console.log语句似乎都没有执行,我很难弄清楚原因。

import { useState, useEffect } from "react";
import config from "../config";
import axios from "axios";

axios.defaults.baseURL = config.backendUrl;

export const useAxios = (axiosParams) => {
  const {  method, url, requestConfig = {} } = axiosParams;

  console.log("above useState");

  const [response, setResponse] = useState([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);

  console.log("below useState");

  useEffect(() => {
    console.log("inside useEffect");
    const controller = new AbortController();

    const fetchData = async () => {
      console.log("inside fetchdata");
      try {
        const res = await axios[method.toLowerCase()](url, {
          ...requestConfig,
          signal: controller.signal,
        });
        console.log("res", res);
        setResponse(res.data);
      } catch (err) {
        console.log(err.message);
        setError(err.message);
      } finally {
        setLoading("fullfilled");
      }
    };

    fetchData();

    // clean up function
    return () => controller.abort();
  }, []);

    return [response, error, loading];
};

在上面的代码中,你可以看到我在useState声明之前和之后都有console.log语句。奇怪的是,useState之前的log语句可以正确执行,但之后的语句却不能。
以下是我使用useAxios的地方:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import config from "../../../config";
import { useAxios } from "../../../CustomHook/useAxios";

const initialState = {
  products: [],
  loading: "idle",
  error: null,
};

export const fetchProducts = createAsyncThunk(
  "products/fetchProducts",
  async (queryParams) => {

    const [product, error, loading] = useAxios({
      method: "GET",
      url: `/get-product-list?${queryParams}`,
    });

    if (loading === "rejected") {
      throw error;
    }

    if (loading === "idle") {
      console.log("lodingggg");
    }

    if (loading === "fullfilled") {
      console.log("fullfied");
    }

    return product; 
  }
);

const productSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchProducts.pending, (state) => {
      state.loading = "pending";
    });
    builder.addCase(fetchProducts.fulfilled, (state, action) => {
      state.loading = "fulfilled";
      state.products = action.payload;
    });
    builder.addCase(fetchProducts.rejected, (state, action) => {
      state.loading = "rejected";
      state.error = action.error.message;
    });
  },
});

export default productSlice.reducer;

我已经检查了我的组件代码,我正确地调用了useAxios钩子。另外,我在控制台中没有看到任何错误。
我尝试了以下方法进行故障排除:
检查组件代码以确保钩子被正确使用。检查控制台是否有任何错误消息。在useState声明之前和之后添加更多的console.log语句以缩小问题范围。尽管做了这些努力,我似乎无法确定为什么useState之后的console.log语句没有运行。
有没有人遇到过类似的问题,或者对如何调试此问题有任何建议?

dw1jzc5e

dw1jzc5e1#

你怎么把钩子弄进来的?useState用于需要默认导出的函数组件中。另外,您不需要在导出中包含您的钩子名称。只需保存钩子文件为“hooks/use-axios.js”并导出组件:
default()=> {.

相关问题