我正在嘗試對反應功能組件進行 axios 呼叫,但生命周期讓我頭疼,因為它不斷回傳“無法讀取未定義的屬性”。我嘗試使用條件渲染以及 await/async 函式,但似乎沒有任何效果。有人可以告訴我我做錯了什么嗎?謝謝
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;
uj5u.com熱心網友回復:
您的渲染方法正在嘗試訪問singleCountry.name.common,但是,您的狀態變數是一個陣列。
將渲染函式更改為:
{singleCountry.map(country => <div><h3>{country.name.common}</h3></div>)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369629.html
標籤:javascript 反应 公理 反应生命周期
