簡體   English   中英

訪問另一個對象內的對象返回無法讀取未定義的屬性

[英]Access an object inside another object returns cannot read property of undefined

我有一個小問題,但由於某種原因我無法解決。

我有一個對象,它是來自 API 的返回請求:

state = { 
        data: []
    }

    componentDidMount() {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=Toronto,CA&appid=${appkey}`)
        .then(data => data.json())
        // .then((data) => {
        //  console.log(data);
        // })
        .then(data => this.setState({data}))

    }

和:

render() {
const weather = this.state.data
console.log(weather.main);

第一部分是在反應組件之前先出現的部分。 我能夠獲取一個對象,然后創建一個返回另一個對象的變量(const),在這種情況下:

{feels_like: 271.85
temp_min: 272.15
temp_max: 276.48
pressure: 1027
humidity: 97}

對於我的無知,奇怪的是,如果我嘗試以這種方式訪問​​例如第一個值(feels_like):

weather.main.feels_like

它會拋出一個錯誤,即無法讀取未定義的屬性“feels_like”。

現在,我嘗試遍歷對象,但它不起作用,我嘗試使用不同的語法訪問該屬性,但仍然拋出錯誤。

我錯過了什么嗎?

目標是創建一個這樣的組件:

console.log(this.state.data);
 const weather = this.state.data;
 return (

  <div>
  <div key={weather.id}>
  <h3>Library Product of the Week!</h3>
  <h4>{weather.name}</h4>
  <h4>{weather.main.temp}</h4>
  <h4>{weather.main.feels_like}</h4>
  <h4>{weather.main.temp_min}</h4>
  <h4>{weather.main.temp_max}</h4>
  <h4>{weather.main.pressure}</h4>
  <h4>{weather.main.humidity}</h4>
  </div>
  </div>
  )
}

這是整個代碼:

import React from 'react'
 import { render } from 'react-dom'

 const appkey = 'xx';

 class Message extends React.Component {

    state = { 
        data: []
    }

    componentDidMount() {
        fetch(`https://api.openweathermap.org/data/2.5/weather?q=Toronto,CA&appid=${appkey}`)
        .then(data => data.json())
        // .then((data) => {
            //  console.log(data);
            // })
            .then(data => this.setState({data}))

        }

        componentDidUpdate() {
            console.log("The component just updated")
        }

        render() {
            console.log(this.state.data);
            const weather = this.state.data;
            return (

                <div>
                <div key={weather.id}>
                <h3>Library Product of the Week!</h3>
                <h4>{weather.name}</h4>
                <h4>{weather.main.temp}</h4>
                <h4>{weather.main.feels_like}</h4>
                <h4>{weather.main.temp_min}</h4>
                <h4>{weather.main.temp_max}</h4>
                <h4>{weather.main.pressure}</h4>
                <h4>{weather.main.humidity}</h4>
                </div>
                </div>
                )
        }
    }

    render(
        <Message />, 
        document.getElementById('root')
        )

從您提供的代碼來看,您似乎已經在第一次將數據保存到狀態之前訪問了數據。 所以你試圖從你的初始狀態的空數組中獲取 Feel_like 值。

為了修復它,您應該在渲染方法中使用它之前檢查您的數據是否存在

編輯:

出於某種原因,API 密鑰對我不起作用,文檔中提到它可能需要幾個小時才能起作用,所以我無法為您測試。 但是代碼沙箱x 在渲染之前檢查數據是否存在。 如果數據未初始化,它將呈現一些文本。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM