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

React开发遇TypeError: Cannot read properties of undefined (reading 'map')报错

错误原因分析
  • 核心报错逻辑:TypeError: Cannot read properties of undefined (reading 'map') 本质是你调用map方法的this.state.weather值为undefined,而非你初始化的空数组
  • 具体代码问题:
    1. 你调用的weatherapi的/current.json接口返回的顶层字段不存在weather属性,实际返回结构包含location、current两个核心顶层字段,因此parsedData.weather取值为undefined,执行setState后覆盖了初始的空数组
    2. 该接口返回的是单个城市的天气对象,不是数组,就算拿到正确值也无法使用map遍历
修复方案

方案1:单城市展示(适配当前接口逻辑)

直接取返回的单个城市数据渲染,无需遍历

import React, {Component} from 'react';
import Body from './Body';

class Weather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weatherInfo: null,
    };
  }

  async componentDidMount() {
    const url = `http://api.weatherapi.com/v1/current.json?key=${this.props.api}&q=Jaipur&aqi=no`;
    let data = await fetch(url);
    let parsedData = await data.json();
    this.setState({
      // 直接存完整返回数据
      weatherInfo: parsedData,
    });
  }

  render() {
    // 数据加载完成前返回空或者加载态
    if (!this.state.weatherInfo) return null;
    return (
      <div className="container">
        <div className="row">
          <div className="col-md-4">
            <Body city={this.state.weatherInfo.location.name} />
          </div>
        </div>
      </div>
    );
  }
}

export default Weather;

方案2:保留map遍历逻辑(适配多城市场景)

如果后续要对接多城市返回的接口,要先确保返回的是数组,同时加判断避免undefined调用map

// render中map调用前加数组判断,同时添加遍历必填的key属性
{Array.isArray(this.state.weather) && this.state.weather.map((element) => {
  return (
    <div className="col-md-4" key={element.location.name}>
      <Body city={element.location.name} />
    </div>
  );
})}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:54:01