简体   繁体   English

React的Json API访问错误

[英]Json API access error with React

I'm trying to access the following variable in Json from an API: 我正在尝试从API访问Json中的以下变量:

page[0].infoBloco[0].tabela[0].dados[0].fonte.nome

I'm getting the error: 我收到错误消息:

TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49

Json that the API returns is this: 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"
                                }
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

The React page code is this: 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) returns the full json console.log(this.state.page)返回完整的json

console.log(this.state.page[0]) returns the first json object console.log(this.state.page[0])返回第一个json对象

console.log(this.state.page[0].infoBloco) returns error TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49 console.log(this.state.page[0].infoBloco)返回错误TypeError: this.state.page[0] is undefined[Learn More] index.jsx:49

I can only access up page [0], when I try to access any more inner element it returns that same error. 我只能访问页面[0],当我尝试访问其他内部元素时,它将返回相同的错误。 Could this error be caused by asynchronous access to the API? 可能是由于异步访问API导致此错误? Can anyone help me fix this? 谁能帮我解决这个问题?

Your component is rendered twice: 您的组件呈现两次:

  1. First render, with state.page = [] , as specified in the constructor 第一次渲染,使用state.page = [] ,在构造函数中指定
  2. After mounting, the page data is loaded and the state is updated ( componentDidMount method) 安装后,将加载页面数据并更新状态( componentDidMount方法)
  3. After the state has been updated, the component is rendered again , this time with the page data in the state 更新状态后, 再次渲染组件,这一次页面数据处于状态

You get the error because when the component is rendered the first time, there is no state.page[0] yet, because the data has not been loaded yet. 之所以会出现错误,是因为第一次呈现组件时,还没有state.page[0] ,因为尚未加载数据。

You can fix your code by adding an if statement to guard against this: 您可以通过添加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>
        )
    }
}

It's common practice to render something like a “loading…” message or a spinner when the component is rendered the first time, without data, like this: 通常的做法是,在第一次渲染组件时,在没有数据的情况下渲染诸如“ loading…”消息或微调框之类的东西,如下所示:

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>
    )
}

do a conditional access as the render gets called before api response which is causing undefined error 在api响应之前调用渲染器进行渲染时进行条件访问,这会导致undefined错误

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

This is definitely due to asynchronous nature of the API call. 这绝对是由于API调用的异步特性。 You should not render your component until API response is updated in the state. 在状态中更新API响应之前,您不应该渲染组件。

Try this in your render method, 在您的渲染方法中尝试一下,

render() {

    if (!(this.state.page && this.state.page.length && this.state.page[0].infoBloco))
      return null;

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

you using try JSON.stringify in react-native 您在react-native中使用try JSON.stringify

  getData = async () => { await fetch('http://localhost:3003/api') .then(resp => resp.json()) .then(data => this.setState({ ...this.state, page: JSON.stringify(data), })) } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM