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