我正在创建一个利用REST国家API的应用程序,我试图在第一次渲染时调用API,根据我的理解,为了做到这一点,你必须在useEffect函数中使用一个空数组,例如
const LightMode = () => {
const data = useRef([])
useEffect(() =>{
axios.get('https://restcountries.com/v3.1/all').then(res=>{
res.data.forEach(country =>{
//console.log(country)
data.current.push({
name: country.name.common,
population: country.population,
region: country.region,
capital: country.capital,
image: country.coatOfArms.png
})
})
})
}, [])
console.log(data)
return(
<div>
<NavigationBar />
<div className='temp'>
<Card className='country-cards'>
<Card.Img variant='top' src={data[0].image}/>
<Card.Body>
<Card.Title></Card.Title>
</Card.Body>
</Card>
</div>
</div>
)
}
但当我运行应用程序时,我得到一个错误,说无法读取未定义,所以第一次渲染在技术上从未运行?我想知道这到底是为什么。我还在学习第一次渲染的工作原理,所以非常感谢任何帮助,如果需要更多信息,请告诉我。
