import './App.css'; import { useEffect, useState } from "react"; import axios from 'axios'; // 添加axios引入 function App() { const [weatherData, setWeatherData] = useState(null); // 修改变量名为weatherData const [selectedCity, setSelectedCity] = useState(''); const [cityList, setCityList] = useState([]); const API_KEY = 'd449610e4ef2fb248bea310f0137ac01'; useEffect(() => { const fetchCityList = async () => { try { const response = await axios.get('https://restapi.amap.com/v3/config/district', { // 修改API地址 params: { key: API_KEY, subdistrict: 1, }, }); setCityList(response.data.districts[0].districts); } catch (error) { console.error('Error fetching city list', error); } } fetchCityList(); }, []); useEffect(() => { const fetchWeather = async () => { if (selectedCity) { try { const response = await axios.get('https://restapi.amap.com/v3/weather/weatherInfo', { params: { key: API_KEY, extension: 'base', city: selectedCity, }, }); setWeatherData(response.data.lives[0]); // 修改对象路径 } catch (error) { console.error('Error fetching weather data:', error); // 修改打印信息 } } else { setWeatherData(null); } }; fetchWeather(); }, [selectedCity]); const handleCityChange = (e) => { setSelectedCity(e.target.value); }; return ( <div className="App"> <h1>天气信息</h1> <label htmlFor="citySelect">选择城市:</label> <select id="citySelect" value={selectedCity} onChange={handleCityChange}> <option value="">请选择城市</option> {cityList.map((city) => ( <option key={city.adcode} value={city.adcode}>{city.name}</option> // 修改option标签内容 ))} </select> {weatherData ? ( <div> <p>城市: {weatherData.city}</p> <p>天气: {weatherData.weather}</p> <p>温度: {weatherData.temperature}℃</p> </div> ) : ( <p>正在获取天气信息...</p> )} </div> ); } export default App;
查询天气全代码
最新推荐文章于 2024-07-19 20:46:11 发布