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

调用OpenWeatherMap API后天气信息无法显示的修复建议

React天气应用API请求无数据返回的修复方案

问题根源排查

原代码存在以下关键错误,导致请求无有效数据返回:

  • 模板字符串使用错误:API URL用单引号包裹,无法解析变量;q=s{city}是笔误,应为q=${city};温度单位参数imperil拼写错误,正确值是imperial。
  • 状态初始化错误:weatherData初始化为数组[{}],但API返回的是单个对象,导致后续判断typeof weatherData.main === 'undefined'逻辑异常。
  • 缺乏错误处理:未处理请求失败(如网络错误、API密钥无效)的情况,无法定位问题。

修复后的完整代码

App.js

import React, { useState } from 'react';
import './App.css';

function App() {
  const apiKey = '你的API密钥'; // 替换为有效OpenWeatherMap API密钥
  const [weatherData, setWeatherData] = useState({}); // 初始化为空对象
  const [city, setCity] = useState('');

  const getWeather = (event) => {
    if (event.key === 'Enter' && city.trim()) { // 增加非空判断,避免空请求
      fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperial&APPID=${apiKey}`
      )
        .then((response) => {
          if (!response.ok) {
            throw new Error('请求失败'); // 处理HTTP错误状态
          }
          return response.json();
        })
        .then((data) => {
          setWeatherData(data);
          setCity('');
        })
        .catch((error) => {
          console.error('获取天气数据失败:', error);
          setWeatherData({ cod: 'error' }); // 设置错误状态提示用户
        });
    }
  };

  return (
    <div className="container">
      <input
        className="input"
        placeholder="输入城市名称..."
        onChange={(e) => setCity(e.target.value)}
        value={city}
        onKeyPress={getWeather}
      />

      {typeof weatherData.main === 'undefined' ? (
        <div>
          <p>欢迎使用天气应用!输入你想查询的城市名称。</p>
        </div>
      ) : (
        <div className="weather-data">
          <p className="city">{weatherData.name}</p>
          <p className="temp">{Math.round(weatherData.main.temp)}℉</p>
          <p className="weather">{weatherData.weather[0].main}</p>
        </div>
      )}

      {weatherData.cod === '404' && <p>未找到该城市,请检查输入。</p>}
      {weatherData.cod === 'error' && <p>获取数据失败,请稍后重试。</p>}
    </div>
  );
}

export default App;

App.css(原样式无需修改)

.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 25px;
 }

 .input {
padding: 15px;
width: 80%;
margin: auto;
border: 1px solid lightgrey;
border-radius: 6px;
font-size: 16px;
 }

 .input:focus{
  outline: none;
 }

 .weather-data{
  margin-top: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
 }

 .city{
  font-size: 30px;
  font-weight: 200;
 }

 .temp{
  font-size: 90px;
  padding: 10px;
  border: 1px solid lightgray;
  border-radius: 12px;
 }

 .weather{
  font-size: 30px;
  font-weight: 200;
 }

额外注意事项

  • 务必替换apiKey为你在OpenWeatherMap官网获取的有效密钥,密钥未激活或额度耗尽也会导致无数据返回。
  • 若需要显示摄氏度,可将units=imperial改为units=metric,同时把温度符号℉替换为℃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:05:26