【问题标题】:React Cannot read property of undefined - Array.map (<anonymous>)React 无法读取未定义的属性 - Array.map (<anonymous>)
【发布时间】:2021-09-22 00:02:41
【问题描述】:

我正在从 api 获取数据并将数据导入 WeatherData.js 并将其作为道具传递给 SmallWeatherCard.js,因为我想稍后将其传递给另一个组件。

当我在 SmallWeatherCard.js 中执行 console.log(data) 时,我可以在控制台中看到整个数据,但是在尝试映射它时出现错误“无法读取未定义的属性”

我在这里做错了什么?

这里的所有代码:Codesanbox

import React from "react";

export const SmallWeatherCard = ({ data }) => {

  return (
    <div>
      {data.properties.timeseries.map((i, index) => (
        <div>
          <ul key={index}>
            <li> {i.data.next_6_hours.summary.symbol_code}
             </li>
            <li>
              {Math.round(i.data.next_6_hours.details.air_temperature_min)}°
            </li>
            <li>|</li>
            <li>
              {Math.round(i.data.next_6_hours.details.air_temperature_max)}°
            </li>
          </ul>
        </div>
      ))}
    </div>
  );
};

【问题讨论】:

  • 您如何使用SmallWeatherCard 组件?该组件未在沙箱中使用,我没有看到任何错误
  • 哪一行导致错误?

标签: reactjs api react-hooks react-props array.prototype.map


【解决方案1】:

您可能正在使用this kinda api。所以,错误是 api 并不总是返回所有字段。例如,在我的情况下,i.data.next_6_hours 没有定义。

所以,试试这样的,

export const SmallWeatherCard = ({ data }) => {
  console.log(typeof data);

  return (
    <div>
      {data.properties.timeseries.map(
        (i, index) =>
          i.data.next_6_hours != null && (
            <div>
              <ul key={index}>
                <li>
                  {Math.round(i.data.next_6_hours.details.air_temperature_min)}°
                </li>
                <li>|</li>
                <li>
                  {Math.round(i.data.next_6_hours.details.air_temperature_max)}°
                </li>
              </ul>
            </div>
          )
      )}
    </div>
  );
};

使用CodeSandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 2021-10-15
    • 1970-01-01
    • 2019-04-09
    • 2020-10-10
    • 2019-02-15
    • 2020-07-23
    • 2019-07-22
    相关资源
    最近更新 更多