如何在 React 中显示天气 api 的数据?

How to display data from a weather api in React?

我正在尝试使用开放天气创建一个简单的天气应用程序 api 以帮助学习 React。 但是我无法在 DOM.

中显示任何数据

想知道是否有人可以帮助我并向我解释我需要做什么,以便我知道未来!谢谢

import React from 'react'
import Titles from './Titles'
import axios from "axios"


const API_KEY = process.env.REACT_APP_WEATHER_API_KEY

class Display extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            data: null
        }
        };
  async componentDidMount() {
       const URL = (`https://api.openweathermap.org/data/2.5/weather?q=taipei,tw&APPID=${API_KEY}`)
       let response = await axios.get(URL);
       let data  = response.data;
       this.setState({ data });
   }




    render(){
    let data = this.state.data
        return(
            <div>
            <Titles />
           <p>{data.description}</p>
           </div>
        );
    }
}
export default Display;

在这个代码示例中,我收到一条错误消息: 无法读取 属性 'description' of null.

以下是api我正在尝试访问和显示温度、描述、城市等:

{
    "coord": {
        "lon": 121.56,
        "lat": 25.04
    },
    "weather": [
        {
            "id": 500,
            "main": "Rain",
            "description": "light rain",
            "icon": "10d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 304.08,
        "pressure": 1001,
        "humidity": 79,
        "temp_min": 302.59,
        "temp_max": 305.93
    },
    "visibility": 10000,
    "wind": {
        "speed": 4.1,
        "deg": 90
    },
    "clouds": {
        "all": 75
    },
    "dt": 1565143170,
    "sys": {
        "type": 1,
        "id": 7949,
        "message": 0.0097,
        "country": "TW",
        "sunrise": 1565126625,
        "sunset": 1565174130
    },
    "timezone": 28800,
    "id": 1668341,
    "name": "Taipei",
    "cod": 200
}

你的初始状态是,

data: null

并且第一次组件以默认状态呈现。所以访问 data.description 会给你错误,因为 data=null.

在使用 componentDidMount 时,您应该始终检查数据是否存在。

试试这个,

<p>{data && data.weather.length > 0 && data.weather.description}</p>

更新

通过查看您的回复数据。

"weather": [
        {
            "id": 500,
            "main": "Rain",
            "description": "light rain",
            "icon": "10d"
        }
    ]

weather节点是数组。你可以这样做,

<p>{data && data.weather.length > 0 && data.weather[0].description}</p>   //display first record

如果你想显示所有的记录,你可以这样做,

{data && data.weather.length > 0 && data.weather.map(weather => {
   return <p>{weather.description}</p>
})}

Demo