【发布时间】:2020-11-27 08:21:32
【问题描述】:
我正在尝试从此 NHL API 获取数据:https://statsapi.web.nhl.com/api/v1/people/8477474/
当我将调用输出到我的页面时,它返回未定义,我无法让它显示值。奇怪的是,对象中的第一个元素正确显示,但没有任何嵌套元素。
这是我的代码
import React, {Component} from "react"
class App extends Component {
constructor() {
super()
this.state = {
loading: false,
player: {}
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://statsapi.web.nhl.com/api/v1/people/8477474/")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
player: data
})
})
}
render() {
const fullname = this.state.loading ? "Loading..." : this.state.player.people[0].fullName;
return (
<div>
{fullname }
</div>
)
}
}
export default App
这不应该返回未定义的,因为键值显然在那里,我相信我的目标是正确的。
我尝试了控制台日志记录,但也未定义。 我也尝试删除 [0] 并执行 this.state.player.people.fullName 和各种替代方案,但没有运气。
【问题讨论】:
标签: javascript reactjs api fetch