TypeError:无法读取未定义的属性(读取“地图”)React JS

Yat*_*ngh 2 javascript reactjs

我面临着错误TypeError: Cannot read properties of undefined (reading 'map')

此代码应该返回卡片标题中的城市名称,该卡片标题是在我的其他文件中定义的,但会引发错误。

代码:

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

class Weather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weather: [],
    };
  }

  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({
      weather: parsedData.weather,
    });
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          {this.state.weather.map((element) => {
            return (
              <div className="col-md-4">
                <Body city={element.location.name} />
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default Weather;
Run Code Online (Sandbox Code Playgroud)

nov*_*imo 6

问题:

在 API 调用之前,您的天气this.state.weather.map数组为空,因此使用会导致错误。

解决方案:

map在使用with arrayes之前有两件重要的事情:

  1. 检查数组的定义(数组是否已定义且存在?)
  2. 检查它的长度(数组是否有一些内容?)

第一的

通过一个简单的语句检查其声明/定义if

{
  if(myArrayOfData) {
    myArrayOfData.map(
      // rest of the codes ...
    )
  }
}

Run Code Online (Sandbox Code Playgroud)

或者使用?人手不足的if

{
  myArrayOfData?.map(
    // rest of the codes ...
  )
}
Run Code Online (Sandbox Code Playgroud)

第二

检查数组的内容并map在检查其长度后使用该函数(这告诉您数据已从 API 调用等到达并准备好处理)

{
  if(myArrayOfData) {
    if(myArrayOfData.length > 0) {
     myArrayOfData.map(
        // rest of the codes ...
     )
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

最后:

虽然上面的代码片段可以正常工作,但您可以通过if同时检查这两个条件来简化它:

{
  if(myArrayOfData?.length > 0) {
     myArrayOfData.map(
        // rest of the codes ...
     )
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,只需对组件的返回进行一些更改Weather

<div className="row">
  {
    if(this.state.weather?.length > 0) {
      this.state.weather.map((element) => {
        return (
          <div className="col-md-4" key={element.id}>  // also don't forget about the passing a unique value as key property
            <Body city={element.location.name}/>
          </div>
        );
      })
    }
  }
</div>
Run Code Online (Sandbox Code Playgroud)

选修的:

在实际示例中,您可能需要在获取数据时显示一些加载组件。

{
  if(myArrayOfData?.length > 0) {
    myArrayOfData.map(
      // rest of the codes ...
    )
  } else {
    <Loading />
  }
}
Run Code Online (Sandbox Code Playgroud)
意识到
const anEmptyArray  = []

if(anEmptyArray){
  // rest of the codes ...
}
Run Code Online (Sandbox Code Playgroud)

比较的结果if(anEmptyArray)始终true为空数组。