【发布时间】: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}° C
</div>
)
: (
<h1>Loading</h1>
)}
</div>
</div>
)
} ```
【问题讨论】:
标签: reactjs api react-hooks state openweathermap