簡體   English   中英

React的Json API訪問錯誤

[英]Json API access error with React

我正在嘗試從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導致此錯誤? 誰能幫我解決這個問題?

您的組件呈現兩次:

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

通常的做法是,在第一次渲染組件時,在沒有數據的情況下渲染諸如“ 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>
    )
}

在api響應之前調用渲染器進行渲染時進行條件訪問,這會導致undefined錯誤

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

這絕對是由於API調用的異步特性。 在狀態中更新API響應之前,您不應該渲染組件。

在您的渲染方法中嘗試一下,

render() {

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

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

您在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