【问题标题】:Cannot Display the Data From the object from an API无法显示来自 API 对象的数据
【发布时间】:2021-11-08 10:27:30
【问题描述】:

我正在使用 ReactJS 制作天气应用程序,而对于天气,我正在使用 OpenWeatherMap API。我已经提取了一个数组和一个对象,因为它们是我感兴趣的。数组包含天气的种类,如下雨或晴天,对象包含温度。我已经能够从数组中提取天气并将其显示在屏幕上,但我无法从对象中提取温度。控制台从未给出任何错误。这是代码:

import React, {useState,useEffect} from 'react'

function WeatherDisplay()
{
    const APIKey = "myKey";

    const [weather, setWeather] = useState([]);

    const [temperature, setTemperature] = useState([]);

    useEffect(() => {
        fetchWeather() ;
    } , []);

    const fetchWeather = async () => {
        const data = await fetch(
            "https://api.openweathermap.org/data/2.5/weather?q=Islamabad&units=metric&appid=" + APIKey
            );
        const weather = await data.json();

        //console.log(weather.weather);
        setWeather(weather.weather);

        console.log(weather.main);
        setTemperature(weather.main);
    } 

    return(
        <section id="w-d-p">
            <div style={
                        {
                            backgroundColor:"rgba(43, 42, 42, 0.575)",
                            width:"100%",
                            height:"100%",
                            display:"flex",
                            flexDirection:"column",
                            justifyContent:"center",
                            alignItems:"center"
                        }
                    } className="container-fluid">
                <div style={
                        {
                            display:"flex",
                            flexDirection:"column",
                            justifyContent:"center",
                            alignItems:"center"
                        }
                    } className="col-sm-12">

                    <h2 id="city">Islamabad</h2>

                    {weather.map(main => (
                        //<h2 key={main.id} id="temp">{main.temp}C</h2>
                        console.log(main.temp)
                    ))}
                    
                    {weather.map(weather => (
                        <h2 key={weather.id} id="weather">{weather.main}</h2>
                    ))}
                </div>
            </div>
        </section>
    )
}

export default WeatherDisplay

抱歉,我不得不删除 API 密钥。 现在在console.log() 之前的return()
它会在控制台中显示温度。我注释掉了 h2 标记并将console.log() 放在那里,现在,控制台给出undefined,然后在下一行打印整个对象,然后在下一行再次打印undefined

所以我发现我没有正确执行map()。请问,我该如何解决这个问题?
这是对象:

main {
    "temp": 28.24,
    "feels_like": 31.43,
    "temp_min": 28.24,
    "temp_max": 28.24,
    "pressure": 1005,
    "humidity": 72,
    "sea_level": 1005,
    "grnd_level": 947
}

还有一件事,我给useState()打了两次电话,可以吗?或者这也可以改进?谢谢!

【问题讨论】:

    标签: reactjs react-hooks openweathermap


    【解决方案1】:

    您不需要为此使用 2 个状态,虽然 weather 是一个数组,但 main 是一个对象

    • 使用一种状态:
    const [weather, setWeather] = useState();
    
    • 将整个天气对象设置为您的状态:
    const fetchWeather = async () => {
      const data = await fetch(
        "https://api.openweathermap.org/data/2.5/weather?q=Islamabad&units=metric&appid=" +
          APIKey
      );
      const weather = await data.json();
      setWeather(weather);
    };
    
    • 因为main 是一个对象,所以你可以像这样渲染它:
    <h2 id="temp">{weather?.main && weather.main.temp}C</h2>
    
    {weather?.weather && weather.weather.map(weather => (
      <h2 key={weather.id} id="weather">{weather.main}</h2>
    ))}
    

    此外,您的 API 在初始渲染后返回,因此 weather 将为 null 可能导致错误,因此有必要在渲染之前检查 weather?.weather

    【讨论】:

    • 嗯,谢谢你的回答,它工作得很好!但是我需要对代码有所了解。是个 ?。三元运算符?而且您没有在对象上使用 map() 函数。这就是我们访问对象的方式吗?再次感谢!
    • ?.optional chaining,这对 js 来说是相当新的。 Array.map() 仅用于循环遍历“Array”,对于对象,您只需直接引用变量本身即可。
    猜你喜欢
    • 1970-01-01
    • 2019-11-04
    • 2019-11-23
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2021-11-23
    相关资源
    最近更新 更多