【发布时间】:2020-08-09 18:55:30
【问题描述】:
我目前正在学习赫尔辛基大学的全栈公开课程,但遇到了一个我无法破解的错误。我正在构建一个从 Rest Country API (https://github.com/apilayer/restcountries) 获取数据的 React Web 应用程序。我正在尝试获取特定国家/地区(例如https://restcountries.eu/rest/v2/alpha/aus)并呈现名称、首都、人口、语言列表和标志。除了语言列表之外的所有内容都可以与此代码完美配合:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const App = () => {
const [ country, setCountry] = useState([])
useEffect(() => {
console.log('effect')
axios
.get('https://restcountries.eu/rest/v2/alpha/aus')
.then(response => {
console.log('promise fulfilled')
setCountry(response.data)
})
}, [])
console.log({country})
return (
<div>
<h1>{country.name}</h1>
<p>Capital: {country.capital}</p>
<p>Population: {country.population}</p>
<h2>Languages</h2>
<h2>Flag</h2>
<img
src={country.flag}
style={{width:200, height:128}}
/>
</div>
);
}
export default App;
但是,当我将以下内容添加到 ...,以尝试呈现语言列表时,我收到错误:“App.js:29 Uncaught TypeError: Cannot read property 'map' of undefined”
<ul>
{country.languages.map(language =>
<li key={language.name}>{language.name}</li>
)}
</ul>
如果有人有任何提示,将不胜感激。
【问题讨论】:
-
如果
country.languages是由axios响应设置的,那么在浏览器收到响应之前,您将无法访问它。
标签: javascript reactjs