我尝试在我的代码中显示来自 API 天气的数据。问题是我不知道如何开始。在这种情况下我需要使用
useEffect
吗?或者也许是事件处理程序?
import { useEffect, useState } from "react";
import { Town, Forecast } from "./type";
const WEATHER_API_KEY = "API KEY HERE";
export default function SearchCity(): JSX.Element {
const [search, setSearch] = useState<string>("");
const [town, setTown] = useState<Town | null>(null);
const [scores, setScores] = useState<Town[]>([]);
const onSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!town) return;
getWeather(town);
setSearch("");
setScores([]);
};
const getLocations = async (value: string): Promise<Town[]> => {
const url = `http://api.openweathermap.org/geo/1.0/direct?q=${value}&limit=3&appid=${WEATHER_API_KEY}`;
const res = await fetch(url);
return await res.json();
};
const onInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const { value } = e.target;
setSearch(value);
if (!value) return;
const locations = await getLocations(value);
setScores(locations);
};
const getWeather = async (town: Town): Promise<Forecast> => {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${town.lat}&lon=${town.lon}&units=metric&appid=${WEATHER_API_KEY}`;
const res = await fetch(url);
return await res.json();
};
const onScoreSelect = (score: Town) => {
setTown(score);
};
useEffect(() => {
if (town) {
setSearch(town.name);
setScores([]);
}
}, [town]);
return (
<form onSubmit={onSubmit}>
<input
className="input"
value={search}
onChange={onInputChange}
type="text"
placeholder="Choose a city"
></input>
<button className="submit" type="submit">
Search
</button>
<ul className="list">
{scores.map((score: Town, index: number) => (
<li key={index}>
<button
className="score-btn"
onClick={() => onScoreSelect(score)}
>
{score.name}
</button>
</li>
))}
</ul>
</form>
);
}
我尝试在互联网上解决我的问题,但我找不到答案(我学习编码,我没有太多经验)。
向 API 发出 HTTP 请求以获取数据,然后使用检索到的数据更新用户界面 (UI)。您可以使用 React 及其“useEffect”钩子来实现此目的,如果需要还可以使用事件处理程序。 首先,设置你的 React 组件:
import React, { useState, useEffect } from 'react';
function WeatherApp() {
const [weatherData, setWeatherData] = useState(null);
useEffect(() => {
// Fetch weather data here
}, []); // Empty dependency array to run the effect only once
return (
<div>
{/* Display weather data here */}
</div>
);
}
export default WeatherApp;
-然后,使用useEffect来获取数据:
useEffect(() => {
// Replace with the actual API endpoint and API key
const apiUrl = 'https://api.anyweather.com/weather';
const apiKey = 'your-api-key';
-最后:
return (
<div>
{weatherData ? (
<div>
<h1>Weather in {weatherData.location}</h1>
<p>Temperature: {weatherData.temperature}°C</p>
<p>Condition: {weatherData.condition}</p>
{/* Other weather information */}
</div>
) : (
<p>Loading weather data...</p>
)}
</div>
);
fetch(`${apiUrl}?apikey=${apiKey}`)
.then((response) => response.json())
.then((data) => {
setWeatherData(data);
})
.catch((error) => {
console.error('Error fetching weather data:', error);
});
}, []);