arrays - 在 JSON 上循环时 "TypeError: Cannot read property ' 名称 ' of undefined"

标签 arrays json reactjs typescript

我有一个像这样的 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: 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>
            ))}

看起来在 map 内我无法获取每张卡的名称或图片??当我控制台记录“cards”时,它会向我显示上面的 JSON,其中包含 name 和 img 属性

最佳答案

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

关于arrays - 在 JSON 上循环时 "TypeError: Cannot read property ' 名称 ' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60581652/

相关文章:

c - 错误 : incompatible types when assigning to type 'char[20]'

java - ArrayList 的数组?

python - 如何在 Python 中使用 JSON 从文件的特定列表中检索特定字符串

android - 如何在 android 中发送 HttpRequest 并获取 Json 响应?

javascript - 当事件步骤更改时,将 StepContent 数据保留在 Material-ui Stepper 中

c++ - std::bind2nd 和 std::bind 与二维数组和结构数组

java - 尝试搜索数组列表时类型不匹配

jquery - 从我的函数中删除 HTML

reactjs - 如何使用 Next.js 和 spring-boot 作为后端服务器?

javascript - 在 React 中 Axios GET 请求出现 ERR_INSUFFICIENT_RESOURCES 错误