【发布时间】:2018-11-28 15:07:59
【问题描述】:
我正在尝试从 API 访问 Json 中的以下变量:
page[0].infoBloco[0].tabela[0].dados[0].fonte.nome
我收到了错误:
TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
API返回的Json是这样的:
[
{
"infoBloco": [
{
"tabela": [
{
"dados": [
{
"fonte": {
"url": "http://www.google.com",
"nome": "Site de buscas"
}
}
]
}
]
}
]
},
{
"infoBloco": [
{
"tabela": [
{
"dados": [
{
"fonte": {
"url": "http://www.yahoo.com",
"nome": "Outro site de buscas"
}
}
]
}
]
}
]
}
]
React 页面代码是这样的:
import React, { Component } from "react"
export default class extends Component {
constructor(props) {
super(props)
this.state = {
page: [],
}
}
componentDidMount() {
this.getData()
}
getData = async () => {
await fetch('http://localhost:3003/api')
.then(resp => resp.json())
.then(data => this.setState({
...this.state,
page: data,
}))
}
render() {
console.log(this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome)
return (
<div>
Exemplo
</div>
)
}
}
console.log(this.state.page) 返回完整的 json
console.log(this.state.page[0]) 返回第一个 json 对象
console.log(this.state.page[0].infoBloco) 返回错误TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49
我只能访问页面 [0],当我尝试访问更多内部元素时,它会返回相同的错误。这个错误可能是由于对 API 的异步访问导致的吗?谁能帮我解决这个问题?
【问题讨论】:
标签: javascript json reactjs async-await