[英]Lifecycle issue on axios call to an external API
I am trying to make an axios call on a react functional component, but the lifecycle is giving me a headache, as it continuously returns "can not read property of undefined".我正在尝试对反应功能组件进行 axios 调用,但生命周期让我头疼,因为它不断返回“无法读取未定义的属性”。 I tried using conditional rendering as well as await/async function, but nothing seems to work.我尝试使用条件渲染以及等待/异步 function,但似乎没有任何效果。 Could someone tell me please what am I doing wrong?有人可以告诉我我在做什么错吗? Thanks谢谢
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;
Your render method is trying to access singleCountry.name.common
, however, your state variable is an array.您的渲染方法正在尝试访问singleCountry.name.common
,但是,您的 state 变量是一个数组。
Change your render function to:将您的渲染 function 更改为:
{singleCountry.map(country => <div><h3>{country.name.common}</h3></div>)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.