【问题标题】:How to get 5 day weather forecast using React Hooks and OpenWeatherMap API如何使用 React Hooks 和 OpenWeatherMap API 获取 5 天天气预报
【发布时间】:2021-05-01 08:10:48
【问题描述】:

所以我希望能够使用 OpenWeatherMap API 和 React 显示所选城市的 5 天天气预报。

我在网上看过一些教程,但它们都使用 Class 组件,我想使用我的使用功能组件和 UseState 钩子。

我有这个工作代码,它允许我获取当前天气、位置名称并显示一个小天气图标。

我希望能够获取 5 天的信息,并将其放入列表中。具体来说,我想要每天的最高、最低、主要、描述和一个图标。

我在进行 API 调用方面真的缺乏经验,所以我很难弄清楚。我有我的 API 密钥,我认为我的 API 调用应该是这样的

https://api.openweathermap.org/data/2.5/weather?q=${placename},IE&appid=${apiKey}&units=metric

placename 是我传递给它的道具,IE 是我的国家代码。

我正在查看本教程,它可以满足我的需求,但它使用了基于类的组件。如果不使用类,我不知道该怎么做。

https://medium.com/@leizl.samano/how-to-make-a-weather-app-using-react-403c88252deb

如果有人能告诉我如何做到这一点,那将不胜感激。这是我当前的代码,它只获取当前温度。



export default function Weather (props) {



// State
const [apiData, setApiData] = useState({});
const [state, setState] = useState('Belfast');


var placename = props.placeprop 


// API KEY AND URL
const apiKey = process.env.REACT_APP_API_KEY;
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${placename},IE&appid=${apiKey}&units=metric`;



useEffect(() => {
  fetch(apiUrl)
    .then((res) => res.json())
    .then((data) => 
        setApiData(data),);
    
}, [apiUrl]);




return (





<div className="weather">
      

      <div>
        {apiData.main ? (
          <div>
            <img
              src={`http://openweathermap.org/img/w/${apiData.weather[0].icon}.png`}
              alt="weather status icon"
            />

               <br/>
              {apiData.name}
              <br/>
              {apiData.main.temp}&deg; C
          </div>

        )

         : (
          <h1>Loading</h1>
        )}
      </div>
    </div>
    


    )


} ```





【问题讨论】:

    标签: reactjs api react-hooks state openweathermap


    【解决方案1】:

    这不是一个完整的答案,但我遇到了这个问题,所以我分享了我所拥有的。

    import React, {useEffect, useState} from 'react';
    
    import css from './Weather.module.css';
    
    function useOpenWeather ({apiKey, lat, lon, units = 'metric'}) {
      const [apiData, setApiData] = useState(null);
    
      const apiUrl = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}`;
    
      useEffect(() => {
        fetch(apiUrl)
          .then((res) => res.json())
          .then((data) => {
              setApiData(data);
          });
      }, [apiUrl]);
    
      return apiData;
    }
    
    function Weather ({lat, lon}) {
      const weather = useOpenWeather({
        apiKey: API_KEY
        lat,
        lon,
        units: 'imperial'
      });
    
      return (
        <div className={css.weather}>
          {weather && weather.daily.slice(0, 5).map(d => (
            <div>
              <img
                src={`http://openweathermap.org/img/w/${d.weather[0].icon}.png`}
                alt={d.weather[0].main}
              />
              <div>{d.temp.max} / {d.temp.min}</div>
            </div>
          ))}
        </div>
      );
    }
    
    export default Weather;
    
    .weather {
      display: grid;
      grid-template-columns: repeat(5, minmax(0, 1fr));
      grid-gap: 16px;
      margin: 16px;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-28
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多