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

React中解构对象嵌套数组时触发TypeError错误求助

React中解构Context内嵌套数组时的类型错误问题

在React应用里,我用useContext钩子获取API返回的天气数据对象,尝试解构嵌套的forecastday数组时,控制台抛出错误:Uncaught TypeError: Cannot read properties of undefined (reading 'forecastday')。但在原生JavaScript里执行完全一样的解构操作却能正常拿到数据,我怀疑问题出在Context.jsx文件里,但找不到具体原因。


数据结构

API返回的天气数据结构如下:

weatherReport = {
  "location": { /* 位置数据 */ },
  "current": { /* 当前天气数据 */ },
  "forecast": {
    "forecastday": [
      {
        "date": "2023-03-07",
        "date_epoch": 1678147200,
        "day": {
          "maxtemp_c": 36.1,
          "maxtemp_f": 97.0,
          "mintemp_c": 17.4,
          "mintemp_f": 63.3,
          "avgtemp_c": 25.6,
          "avgtemp_f": 78.1,
          "maxwind_mph": 9.6,
          "maxwind_kph": 15.5,
          "totalprecip_mm": 0.0,
          "totalprecip_in": 0.0,
          "totalsnow_cm": 0.0,
          "avgvis_km": 10.0,
          "avgvis_miles": 6.0,
          "avghumidity": 22.0,
          "daily_will_it_rain": 0,
          "daily_chance_of_rain": 0,
          "daily_will_it_snow": 0,
          "daily_chance_of_snow": 0,
          "condition": {
            "text": "Sunny",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
            "code": 1000
          },
          "UV": 7.0
        }
      }
      // 更多预报数据项
    ]
  }
}

React组件代码

使用useContext的组件代码:

import { useGlobalContext } from "../context"

const ForecastReport = () => {
  const { forecast: { forecastday: [...forecastday] } } = useGlobalContext()

  console.log(forecastday)

  return <div className="forecast-box">
    Forecast Report
  </div>
}

export default ForecastReport

控制台错误

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

原生JavaScript对比测试

在原生JS中执行相同解构逻辑,能正常获取数据:

const {forecast:{forecastday:[...forecastday]}} = weatherReport
console.log(forecastday);

原生JS控制台输出

(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:53