[英]how to set data in React with axios?
how to show name and id in <h1>
this project get api with axios如何在<h1>
中显示名称和 ID这个项目得到 api 和 axios
import React, { useState } from "react";
import axios from "axios";
const Details = () => {
const [data, setData] = useState({
name: "",
id: "",
});
const apiDetails = () => {
axios
.get(`https://api.coingecko.com/api/v3/coins/${"ethereum"}`)
.then((response) => {
// console.log(response);
setData({
name: response.data.name,
id: response.data.id,
});
return setData;
});
};
return (
<div>
<h1>{setData.name}</h1>
<h1>{data.name}</h1>
<h1>{setData.id}</h1>
<h1>{data.id}</h1>
<h1>{setData.name}</h1>
</div>
);
};
export default Details;
You should use a useEffect
as so, you can learn more about this hook here你应该使用useEffect
,你可以在这里了解更多关于这个钩子的信息
import React, { useState, useEffect } from "react";
import axios from "axios";
const Details = () => {
const [data, setData] = useState(null);
const apiDetails = () => {
axios
.get(`https://api.coingecko.com/api/v3/coins/${"ethereum"}`)
.then((response) => {
// console.log(response);
//setData({
// name: response.data.name,
// id: response.data.id,
// });
return response;
});
};
useEffect(() => {
(async () => {
const response = await apiDetails();
setData({
name: response.data.name,
id: response.data.id,
});
})();
}, [])
if (data) {
return (
<>
<h1>{data.name}</h1>
<h1>{data.id}</h1>
</>
);
}
return null;
};
export default Details;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.