JSON遍历时出现"TypeError: Cannot read property 'name' of undefined"错误

3

我有一个类似这样的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"
    }
  ]
}


我想循环这些对象,并使用每个对象的img属性渲染一个具有backgroundImage的div。
我尝试过这样做,但它告诉我:
TypeError:无法读取未定义的属性“name”。
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?当我控制台记录“cards”时,它显示了上述具有名称和img属性的JSON。


你的 JSON 没问题,我可以循环遍历它。你能创建一个代码沙盒吗? - blueseal
cards.json中的数据为什么需要存储在state中? - goto
2个回答

0
假设您的代码被包装在一个函数组件中(见下文),那么您导入/使用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组件相同的文件夹中,我没有输出图像,并且我已更新了依赖数组。

0
如果你只想显示卡片,那么它们没有必要在 useEffect 中。我建议你创建一个常量,并用 cardsJson.cards 初始化它,例如:
const cards = cardsJson.cards;

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

const [cards, setCards] = useState(cardsJson.cards);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接