我正在从API读取数据,并且试图使用React在HTML的select标签中显示数据数组中的元素,但是它一直告诉我即使该数据也不是数组好像是在我做console.log时。
render(){
console.log(this.state.countries.Countries)
return(
<div className = "tables-container">
<h1>Tables</h1>
<label>Please Select a Country to view data for: </label>
<select name = "countries" id = "countries">
<option selected = "selected">Select a Country</option>
{
this.state.countries.Countries.map((data)=>(
<option>{data.Country}</option>
))
}
</select>
</div>
)
}
运行此命令时,它显示“ TypeError:无法读取未定义的属性'map'。” console.log结果显示为
(188) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
所以我很确定this.state.countries.Countries
应该是一个数组,因此map函数应该可以,但是不能。
在我的构造函数中,我有
this.state = {
countries: [],
}
并且我已经获取了API
componentDidMount(){
fetch("https://api.covid19api.com/summary")
.then((data) => data.json())
.then((data) => {
this.setState({
countries: data
})
})
}
我已经坚持了一个小时,现在我真的需要帮助弄清楚它。谢谢!
答案 0 :(得分:1)
this.state = {
countries: [],
}
this.state.countries
从一个空数组开始。它没有.Countries
属性,因此对于您的第一个渲染,this.state.countries.Countries
是undefined
,并且您无法映射undefined
。
在加载数据之前和之后,您需要状态具有相同的形状。因此,如果您想要.countries.Countries
嵌套,请将您的初始状态更改为:
this.state = {
countries: {
Countries: []
}
}
如果您只想嵌套一层,请保留初始值并更改以下内容:
// In componentDidMount
this.setState({
countries: data.Countries
})
// In render
this.state.countries.map(