开发者问题收集

在 JSON 上循环时出现“TypeError:无法读取未定义的属性‘name’”

2020-03-07
658

我有这样的 JSON:

{
  "cards": [
    {
      "name": "aquaman",
      "img": "aquaman.png"
    },
    {
      "name": "batman",
      "img": "batman.png"
    },
    {
      "name": "captainamerica",
      "img": "captainamerica.png"
    },
    {
      "name": "deadpool",
      "img": "deadpool.png"
    },
    {
      "name": "flash",
      "img": "flash.png"
    },
    {
      "name": "greenlantern",
      "img": "greenlantern.png"
    },
    {
      "name": "ironman",
      "img": "ironman.png"
    },
    {
      "name": "spiderman",
      "img": "spiderman.png"
    },
    {
      "name": "ironfist",
      "img": "ironfist.png"
    },
    {
      "name": "thepunisher",
      "img": "thepunisher.png"
    },
    {
      "name": "wonderwoman",
      "img": "wonderwoman.png"
    },
    {
      "name": "xman",
      "img": "xman.png"
    }
  ]
}

我想循环这些对象并渲染一个带有 backgroundImage 的 div,每个对象都有 img 属性,

我试过了,但它告诉我:

TypeError: Cannot read property 'name' of undefined

import React, { useEffect, useState } from "react";
import cardsJson from "../../../utils/cards.json";

const [cards, setCards] = useState();

useEffect(() => {
    setCards(cardsJson.cards);
  }, [cards]);

{cards &&
            cards.map((card: any, index: number) => (
              <div key={card.name} className="cardHero">
                <div className="front"></div>
                <div
                  className="back"
                  style={{
                    backgroundImage: `url(${require(`../../../assets/images/${card.img}`)})`
                  }}
                ></div>
              </div>
            ))}

看起来在地图内部我无法获取每张卡片的名称或图片?当我控制台记录“卡片”时,它向我显示了带有名称和 img 属性的 JSON,如上所示

2个回答

假设您的代码包装在函数组件中(见下文),则可能是您导入/使用 cards.json 的方式存在问题。此外,在 useEffect 中,将依赖项数组改为 [] 而不是 [cards]。我将您的代码更改为此,它就可以正常工作:

import React, { useEffect, useState } from "react";
import cardsJson from "./cards.json";


export function Cards() {
  const [cards, setCards] = useState();

  useEffect(() => {
    console.log(cardsJson);
    setCards(cardsJson.cards);
  }, []);

  return (
    <div>
      {
        cards &&
        cards.map((card, index) => (
          <div key={card.name} className="cardHero">
            <div className="front">{card.name}</div>
            <div
              className="back"
            ></div>
          </div>
        ))
      }
    </div>
  );
}

注意,我将 cards.json 放在与 Cards 组件相同的文件夹中,我没有输出图像,并且我更新了依赖项数组。

Troy
2020-03-07

如果您只想显示卡片,则没有必要将它们放在 useEffect 中。我建议您创建一个常量并使用 cardsJson.cards 初始化它,例如:

const cards = cardsJson.cards;

或者,如果您想使用状态,只需使用 cardsJson.cards 初始化您的状态,例如:

const [cards, setCards] = useState(cardsJson.cards);
Pedro W. Botelho
2020-03-07