[英]React: How to get data from Axios, not Promise?
I'm trying to get data from a link but all I get is a Promise.我正在尝试从链接获取数据,但我得到的只是 Promise。 Here is my example code:这是我的示例代码:
import axios from "axios";
export default function App() {
const url = `https://finnhub.io/api/v1/stock/profile2?symbol=GME&token=c6a500qad3idi8g5o2v0`;
const fetchData = async (u) => {
return await axios.get(u).then((res) => res.data);
};
return (
<div className="App">
<button onClick={() => console.log(fetchData(url))}>click me</button>
</div>
);
}
I don't know which part of the code is wrong that it keeps giving out the Promise like the photo here:我不知道代码的哪一部分是错误的,它不断给出 Promise 就像这里的照片:
Please help.请帮忙。 I appreciate it!我很感激!
You can do it like this你可以这样做
import axios from "axios";
export default function App() {
const url = `https://finnhub.io/api/v1/stock/profile2?symbol=GME&token=c6a500qad3idi8g5o2v0`;
const [data, setData] = React.useState(null);
const fetchData = async (u) => {
return await axios.get(u).then((res) => {
setData(res.data);
console.log(res.data.name);
});
};
return (
<div className="App">
<button onClick={() => fetchData(url)}>click me</button>
Name :{data?.name}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.