【发布时间】:2022-01-15 06:50:04
【问题描述】:
我有一个JSON 文件,其中包含 3 个不同的对象(card1、card2 和 card3)。
我想遍历JavaScript 中的这些对象,将它们转换为对象的array,然后在我的 React 代码中,我试图根据 JSON 文件中有多少将它们转换为组件。
到目前为止我所拥有的:
import Card from "./card-elements/Card";
import json from "./data.json";
const list = [];
for (const key in json) {
if (json.hasOwnProperty(key)) {
list.push(key);
}
}
function App() {
return (
<div className="card-area">
{list.map(i => {
return <Card title={i.title}
description={i.description}
borderColor={"red"}/>
})}
</div>
);
}
export default App;
data.json:
{
"card1": {
"title": "Card One",
"description": "This is card one's description. Straight from JSON file!"
},
"card2": {
"title": "Card Two",
"description": "Directly from the JSON file, this is card two's description"
},
"card3": {
"title": "Card Three",
"description": "And finally, this is the last cards description!"
}
}
电流输出: 我的 React 没有出现错误,它只显示一个组件,并且“标题”和“描述”没有显示
任何帮助将不胜感激,谢谢!
【问题讨论】:
标签: javascript reactjs json