reactjs - 类型错误:运行时出现无法读取未定义的属性“地图”
问题描述
每次我将 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
解决方案
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>
)
}
推荐阅读
- php - 只有 PHP 和 CSS 的砌体布局?
- wordpress - 页脚不使用全宽显示谷歌地图 iframe
- javascript - 数组值未添加到 Firestore
- javascript - 角度材料设计输入字段,防止在单击输入时将焦点设置到下一个输入元素
- c++ - C ++:初始化(新)不同初始大小的向量数组
- javascript - 如何将标签放在 PHP 变量中?
- javascript - 为什么 Promise 返回也 Resolve on Reject
- ajax - 不推荐使用 Ajax 加载 PHP $HTTP_RAW_POST_DATA
- c# - 使用 foreach 迭代时跳过类的一些属性
- java - 异常java后继续代码