TypeError: Cannot read property 'get' of undefined with useEffect and Axios

TypeError: Cannot read property 'get' of undefined with useEffect and Axios

我正在尝试在 React 挂钩中获取一些数据。这里没什么特别的,只是一些加载文本,然后在我的数据加载后替换。

但我一直在点击我的 catch 块并在控制台上打印 Failed to fetch data: Cannot read property 'get' of undefined TypeError: Cannot read property 'get' of undefined

import React, { useState, useEffect } from "react";
import { axios } from "axios";

const DataPanel = () => {
  let [isLoading, setLoading] = useState(false);
  let [data, setData] = useState();

  useEffect(() => {
    async function getData() {
      let response;
      setLoading(true);
      try {
        response = await axios.get("urltosomewhere");
        setData(response);
      } catch (e) {
        console.log(`Failed to fetch data: ${e.message}`, e);
        return;
      } finally {
        setLoading(false);
      }
    }

    getData();
  });

  return (
    <div>
      <div>{isLoading ? <span>Loading...</span> : <span>{data}</span>} </div>
    </div>
  );
};

export default DataPanel;

您需要 import axios from 'axios',而不是 import { axios } from 'axios'

这是因为 axios 模块默认导出 axios class。它不是命名导出,因此无法使用您尝试的方法导入。