应用.js:29 未捕获类型错误:无法读取未定义的属性'map'



我目前正在学习赫尔辛基大学的全栈公开课程,我的听力因为一个我无法破解的错误而崩溃。我正在构建一个React网络应用程序,从其他国家API获取数据(https://github.com/apilayer/restcountries)。我想找一个特定的国家(例如。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:无法读取未定义的属性"map">

<ul>
{country.languages.map(language =>
<li key={language.name}>{language.name}</li>
)}
</ul>

如果有人有什么建议,我们将不胜感激。

当country仍然等于[]时,它在第一次渲染时出错。因此,在第一次渲染时,它尝试调用[]上的temap方法,该方法未定义,也没有map方法。

如果设置了country.languages,您可以通过添加一个复选框来解决此问题,例如:

<ul>
{country.languages && country.languages.map(language =>
<li key={language.name}>{language.name}</li>
)}
</ul>

map方法现在只会在设置country.languages时被激发。

您可以使用?。运算符以避免多重&amp;检查。您的代码将是country?。语言?。映射

最新更新