我有一個JSON檔案,里面有 3 個不同的物件(card1、card2 和 card3)。我想在 中遍歷這些物件JavaScript,將它們轉換為arrayof 物件,然后在我的 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;
資料.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 沒有出現錯誤,它只顯示一個組件,并且沒有顯示“標題”和“描述”
任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
無需將每個專案推送到 alist并使用它。而不是使用Object.entries。
像這樣嘗試
function App() {
return (
<div className="card-area">
{(Object.entries(json) || []).map(([key, value]) => {
return (
<Card
title={value.title}
description={value.description}
borderColor={"red"}
/>
);
})}
</div>
);
}
uj5u.com熱心網友回復:
在 React 中,您應該使用 useState 鉤子來更新組件。
Try something like:
import Card from "./card-elements/Card";
import json from "./data.json";
function App() {
const [cardData, setCardData] = React.useState();
React.useEffect(() => {
const list = [];
for (const key in json) {
if (json.hasOwnProperty(key)) {
list.push(key);
}
}
}, [])
return (
<div className="card-area">
{cardData && list.map(i => {
return <Card title={i.title}
description={i.description}
borderColor={"red"}/>
})}
</div>
);
}
匯出默認應用程式;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378835.html
標籤:javascript 反应 json
上一篇:如何從元素陣列回傳到新陣列?
下一篇:如何使用公會ID獲取公會物件
