TypeError:无法使用useEffect和Axios读取未定义的属性“ get”

时间:2020-05-07 16:48:12

标签: reactjs async-await axios use-effect use-state

我正在尝试在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;

1 个答案:

答案 0 :(得分:3)

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

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