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

React调用天气API触发Objects are not valid as a React child报错求助

问题原因

  • 你定义的getWeatherFromApiAsync是直接返回Promise的函数,当你把它当做组件直接在React中渲染时,React拿到的是未执行完成的Promise对象,无法将其作为合法子元素渲染,这是触发报错的直接原因。
  • 你调用的当前OpenWeather接口返回的是单个城市的天气对象,不是数组,直接对responseJson调用map方法也会触发额外的运行时报错。

解决方案

按照React标准异步数据请求写法,使用useState存储接口返回的天气数据,使用useEffect在组件挂载时发起请求,拿到数据后更新状态再渲染内容,参考代码如下:

import { useState, useEffect } from 'react';

export default function WeatherComponent() {
  // 定义存储天气数据、加载状态、错误状态的变量
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 组件挂载时发起请求
    const fetchWeather = async () => {
      try {
        const response = await fetch(
          "https://api.openweathermap.org/data/2.5/weather?q=brighton,uk&appid=8b609354454cdb6c5a7092a939861ace&units=metric"
        );
        if (!response.ok) throw new Error('请求失败');
        const data = await response.json();
        setWeatherData(data);
      } catch (err) {
        setError(err.message);
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchWeather();
  }, []); // 空依赖数组保证只在组件挂载时请求一次

  // 加载状态兜底
  if (loading) return <div>加载中...</div>;
  // 错误状态兜底
  if (error) return <div>请求出错:{error}</div>;
  // 数据返回后渲染内容
  return (
    <div className="App">
      <div>
        <h6>经度:{weatherData.coord.lon}</h6>
        <h6>纬度:{weatherData.coord.lat}</h6>
        <h6>当前温度:{weatherData.main.temp}℃</h6>
      </div>
    </div>
  );
}

后续直接把WeatherComponent当做普通组件在需要的位置引入渲染即可,不要直接调用异步函数当做组件使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:36:05