首页 > 解决方案 > 类型错误:运行时出现无法读取未定义的属性“地图”

问题描述

每次我将 map 函数与 axios 一起使用时,都会出现以下错误。

TypeError:无法读取未定义的属性“地图”

API调用的反应代码:

import React ,{Component} from 'react'
import axios from 'axios'
 class Api extends Component{
     state={
         content :[]
     }
componentDidMount =()=>{
    axios.get('js/data.json').then(res=>{this.setState({content : res.data.content})
                                        console.log(this.state.content)})
}

    render(){
        const items=this.state.content ;
        const thecontain= items.map((item)=>{
            return(
            <div>
            <p>{item.name}</p>  
            </div>
            )
        })
                              
            return(
           
     <div>{thecontain}</div>
   )}
}
export default Api

标签: reactjs

解决方案


    render(){
    const items=this.state.content;
    let thecontain = null; 
    if(typeof this.state.content === 'object'){
      if(this.state.content.constructor.name == "Array"){
         thecontain= items.map((item)=>{
        return (
           <div>
            <p>{item.name}</p>  
           </div>
        )
      })
     }
    }
        return(
       
        <div>{thecontain}</div>
     )
  }
 

推荐阅读