【发布时间】:2021-11-29 16:15:10
【问题描述】:
我正在尝试对 react 功能组件进行 axios 调用,但生命周期让我很头疼,因为它不断返回“无法读取未定义的属性”。 我尝试使用条件渲染以及等待/异步函数,但似乎没有任何效果。 有人可以告诉我我做错了什么吗? 谢谢
import axios from "axios";
import { useParams } from "react-router-dom";
const SingleCountry = () => {
let params = useParams();
const [singleCountry, setSingleCountry] = useState([]);
useEffect(() => {
const getSingleCountry = () => {
axios
.get(`https://restcountries.com/v3.1/name/${params.name}`)
.then((country) => setSingleCountry(country.data))
.catch((error) => console.log(`${error}`));
};
getSingleCountry();
}, []);
return (
<div>
<h1>Single Country</h1>
{singleCountry.length > 0 && (
<div>
<h3>{singleCountry.name.common}</h3>
</div>
)}
</div>
);
};
export default SingleCountry;
【问题讨论】:
标签: javascript reactjs axios react-lifecycle