You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现下拉选城市触发Axios请求获取天气的问题求助

解决React下拉选择城市切换天气数据的问题

你的代码核心问题在于未正确关联下拉选择与API请求的触发逻辑,同时状态管理和组件props的使用存在不合理之处,以下是具体修复方案:

问题分析

  • 下拉选择框(<select>)未绑定onChange事件,选择城市后无法触发状态更新
  • App组件接收的searchCities props不符合根组件使用场景,应自行维护当前选中城市的状态
  • city初始状态设为数组[],但API返回的是对象,会导致渲染时访问city.main报错
  • 切换城市时未重置isLoading状态,无法正确显示加载提示

修复后的完整代码

import React, { useEffect, useState } from "react";
import axios from "axios";
import "./App.css";

function App() {
  // 初始化city为null,避免渲染时访问属性报错
  const [city, setCity] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  // 组件内部维护选中城市状态,无需外部props
  const [selectedCity, setSelectedCity] = useState("");

  // 建议将API密钥存入环境变量,避免泄露
  const API_KEY = "08acd577f8ab8cabf637f7cd3736a629";

  useEffect(() => {
    // 未选中城市时不发起请求
    if (!selectedCity) return;

    setIsLoading(true);
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${selectedCity}&units=metric&appid=${API_KEY}`;
    
    axios.get(url)
      .then((response) => {
        setCity(response.data);
      })
      .catch(err => {
        console.error("获取天气数据失败:", err);
        // 可在此添加错误提示逻辑
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [selectedCity]); // 依赖选中城市状态,城市变化时自动触发请求

  // 处理下拉选择事件
  const handleCityChange = (event) => {
    setSelectedCity(event.target.value);
  };

  if (isLoading) {
    return <h2>加载中...</h2>;
  }

  // 未选中城市时显示提示
  if (!city) {
    return (
      <div>
        <select onChange={handleCityChange} value={selectedCity}>
          <option value="">选择城市</option>
          <option value="Dallas">达拉斯</option>
          <option value="London">伦敦</option>
        </select>
        <p>请选择一个城市查看天气</p>
      </div>
    );
  }

  return (
    <div>
      <select onChange={handleCityChange} value={selectedCity}>
        <option value="">选择城市</option>
        <option value="Dallas">达拉斯</option>
        <option value="London">伦敦</option>
      </select>
      <h3>城市: {city.name}</h3>
      <h3>湿度: {city.main.humidity}%</h3>
      <h3>温度: {city.main.temp}°C</h3>
      <h3>天气: {city.weather[0].description}</h3>
    </div>
  );
}

export default App;

关键修改点

  • 移除不必要的searchCities props,改为组件内部维护selectedCity状态
  • 给<select>绑定onChange事件,选择城市时更新状态并触发API请求
  • 调整useEffect依赖为selectedCity,实现城市切换自动请求数据
  • 优化加载状态处理,每次请求前重置加载状态,请求完成后统一关闭加载提示
  • 增加无选中城市时的提示逻辑,避免空状态报错
  • 建议将API密钥存入环境变量(如.env文件中的REACT_APP_OPENWEATHER_API_KEY),不要硬编码在代码中

内容的提问来源于stack exchange,提问作者user11130151

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 07:28:10