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

React天气应用调用OpenWeatherMap API无法读取city.name属性求助

天气应用API调用无法访问name属性的问题解决

问题说明

开发天气应用时,调用OpenWeatherMap API后无法访问响应中的city.name属性,抛出类型错误。

API响应示例

{
  "cod": "200",
  "message": 0,
  "cnt": 40,
  "list": [],
  "city": {
    "id": 745042,
    "name": "Istanbul",
    "coord": {},
    "country": "TR",
    "population": 11581707
  }
}

现有组件代码

import axios from "axios"
import { useEffect, useState } from "react"

function ApiCall({ getCities }) {
    const[data, setData] = useState({})

    useEffect(() => {
        axios(`https://api.openweathermap.org/data/2.5/forecast?q=Istanbul&appid=c681e6e33ec339728fdf88e0b24a2a01`)
        .then(res => console.log(res.data))
        .catch(err=> console.log(err))
    })

    const { city, list } = data
    console.log(city.name)
}

错误信息

Uncaught TypeError: Cannot read properties of undefined (reading 'name')

问题原因及修复方案

核心问题1:未将API数据存入state

原代码仅打印了API返回结果,没有调用setData更新组件状态,导致data始终是初始空对象,city为undefined,访问city.name必然报错。

核心问题2:useEffect无依赖数组,引发无限请求

useEffect未设置依赖数组,会在组件每次渲染时重复发起API请求,既浪费资源也可能引发异常。

核心问题3:初始状态为空,未做空值判断

组件首次渲染时API请求还未完成,data.city不存在,直接访问city.name触发空值错误。

修复后的代码

import axios from "axios"
import { useEffect, useState } from "react"

function ApiCall({ getCities }) {
    const[data, setData] = useState({})

    useEffect(() => {
        axios(`https://api.openweathermap.org/data/2.5/forecast?q=Istanbul&appid=c681e6e33ec339728fdf88e0b24a2a01`)
        .then(res => setData(res.data)) // 将返回数据存入state
        .catch(err=> console.log(err))
    }, []) // 添加空依赖数组,仅执行一次请求

    // 使用可选链操作符避免空值报错
    console.log(data.city?.name)
}

额外优化建议

如果需要在组件中渲染数据,建议配合条件渲染避免加载阶段报错:

if (!data.city) {
  return <div>加载中...</div>
}

return (
  <div>
    <h1>{data.city.name}</h1>
    {/* 后续渲染list数据逻辑 */}
  </div>
)

内容的提问来源于stack exchange,提问作者Recep Çankaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:39:40