【问题标题】:TypeError: Cannot read property 'get' of undefined with useEffect and AxiosTypeError:无法使用 useEffect 和 Axios 读取未定义的属性“get”
【发布时间】:2020-08-23 01:46:42
【问题描述】:

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

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


【解决方案1】:

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

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

【讨论】:

  • 是的……我有时是瞎子。谢谢你
  • 不用担心 :) 发生在我们最好的人身上 :)
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 2020-07-14
  • 2017-08-30
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多