我试图在React挂钩中获取一些数据。这里没什么好看的,只是一些加载文本,然后一旦我的数据加载就替换掉。
但是我一直打我的陷阱,并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
类。它不是命名导出,因此无法使用您尝试的方法导入。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句