类型错误,无法读取未定义的属性“地图”

问题描述

我正在从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
                })
            })
    }

我已经坚持了一个小时,现在我真的需要帮助弄清楚它。谢谢!

解决方法

this.state = {
    countries: [],}

this.state.countries从一个空数组开始。它没有.Countries属性,因此对于您的第一个渲染,this.state.countries.Countriesundefined,并且您无法映射undefined

在加载数据之前和之后,您需要状态具有相同的形状。因此,如果您想要.countries.Countries嵌套,请将您的初始状态更改为:

this.state = {
  countries: {
    Countries: []
  }
}

如果您只想嵌套一层,请保留初始值并更改以下内容:

// In componentDidMount
this.setState({
  countries: data.Countries
})

// In render
this.state.countries.map(

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...