React天气预报

app.js

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 = 'b5076082474b92a8ce29afcf82bf0345';

  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">
        <h2>天气信息</h2>
        <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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值