gpt4 book ai didi

javascript - React 的 Json API 访问错误

转载 作者:行者123 更新时间:2023-11-30 06:55:06 25 4
gpt4 key购买 nike

我正在尝试从 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[了解更多] index.jsx: 49

我只能访问页面 [0],当我尝试访问任何更多内部元素时,它返回相同的错误。这个错误会不会是异步访问API导致的?谁能帮我解决这个问题?

最佳答案

你的组件被渲染了两次:

  1. 首先呈现,使用 state.page = [],如构造函数中指定的那样
  2. 挂载后加载页面数据并更新状态(componentDidMount方法)
  3. 状态更新后,组件再次呈现,这次页面数据处于状态

你得到这个错误是因为当第一次渲染组件时,还没有 state.page[0],因为数据还没有加载。

您可以通过添加 if 语句来防止出现这种情况来修复您的代码:

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() {

if (this.state.page[0]) {
console.log(this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome)
}

return (
<div>
Exemplo
</div>
)
}
}

通常的做法是在第一次渲染组件时渲染诸如“正在加载...”消息或微调器之类的东西,没有数据,如下所示:

render() {

if (!this.state.page[0]) {
return <div>Loading, please wait…</div>
}

return (
<div>
Exemplo: {this.state.page[0].infoBloco[0].tabela[0].dados[0].fonte.nome}
</div>
)
}

关于javascript - React 的 Json API 访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com