【发布时间】:2021-07-14 18:34:02
【问题描述】:
我正在尝试使用 React 中的 fetch 映射 JSON 数据,但我的 map 语句出现错误。我做错了什么?
class Carbon extends Component {
constructor() {
super()
this.state = {
data: []
}
}
render() {
return (
<div>
<h5>Co2 Emissions</h5>
<h5>Co2 Per Capita</h5>
{this.state.data.map(data => data.data)}
</div>
)
}
componentDidMount() {
fetch('https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.json')
.then( resp => resp.json())
.then((data)=> {
this.setState({
data: data.url
})
console.log(data)
})
}
}
export default Carbon
【问题讨论】:
-
当你尝试
map()时,这意味着this.state.data是undefined。很可能,fetch()在componentDidMount()中返回的data没有属性url。您可以尝试将其记录到控制台。