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

React中如何遍历数组逐个传参调用API获取所有城市数据

问题根因
  • 直接将城市数组拼接为字符串传入单城市查询接口,接口仅能识别第一个逗号前的城市参数,因此仅返回德里的天气数据。
  • 原有批量请求逻辑未将返回结果存入组件状态,且存在变量名冲突:getAllCities内部定义的cities变量覆盖了外层静态城市数组,导致逻辑混乱。
  • 在组件顶层作用域直接判断状态并执行setState,会触发React无限重渲染报错,不符合React状态更新规则。
  • 渲染逻辑错误读取静态城市数组的temp、temp_min等属性,数组本身不存在这些字段,无法正常展示数据。
修复后完整代码
import { useState, useEffect } from 'react';

const WeatherPanel = () => {
  // 存储所有城市的天气返回数据
  const [citiesWeather, setCitiesWeather] = useState([]);
  // 静态城市列表
  const cities = ["Delhi","Dehradun","Kotdwara","Pune"];

  // 单城市天气请求方法
  const getCity = async (cityName) => {
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=7938d9005e68d8b258a109c716436c91`;
    const response = await fetch(url);
    const resJson = await response.json();
    // 同步返回城市名+对应天气数据,方便渲染
    return {
      cityName: cityName,
      weatherData: resJson.main
    }
  };

  // 批量并发请求所有城市数据
  const getAllCities = async() => {
    const requestPromises = cities.map(city => getCity(city))
    const allCitiesResult = await Promise.all(requestPromises);
    setCitiesWeather(allCitiesResult);
  }

  // 组件首次挂载时触发一次请求即可
  useEffect(() => {
    getAllCities();
  }, []);

  return(       
    <div>
      {citiesWeather.length === 0 ? (
        <p className="errorMsg">数据加载中...</p>
      ) : (
        citiesWeather.map((item, index) => (
          <div className="info" key={index}>
            <h2 className="location">
              <i className="fa-solid fa-street-view"> </i>{item.cityName}
            </h2>
            <h1 className="temp">
              {item.weatherData.temp}℃
            </h1>
            <h3 className="tempmin_max">
              Min : {item.weatherData.temp_min}℃ | Max : {item.weatherData.temp_max}℃
            </h3>
          </div>
        ))
      )}
    </div>
  )
}

export default WeatherPanel;
核心调整点
  • 移除顶层直接更新状态的错误逻辑,避免无限重渲染问题,仅在组件首次挂载时触发批量请求。
  • 用Promise.all并发发起所有城市的请求,比逐个串行请求效率更高。
  • 新增独立状态存储所有城市的接口返回结果,修正原有变量名冲突问题,静态配置、接口返回值、单条数据命名边界清晰。
  • 渲染逻辑改为遍历天气结果数组,逐个输出每个城市的温度信息,不再读取静态数组上不存在的属性。
  • 单城市请求返回结果中保留传入的城市名,避免接口返回名称和预期不一致导致的展示错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 14:06:27