[英]Mapping Array of Objects React
所以我目前在這里遇到了一個小問題。 所以我有這個組件,它從 JSON 獲取數據,我有鏈接,但顯示的次數是 20 倍。 我在 JSON 文件中擁有相同數量的對象。 我知道這是問題{data.map((postData)
,它正在映射 JSON 文件中的所有對象,當我想要唯一的( classE
, priceE
和imageE
)顯示時。
import React from "react";
import data from "./data.json";
import { Link } from "react-router-dom";
function E() {
return (
<div>
{data.map((postData) => {
return (
<div key={postData.id} className="m-4 bg-blue-100 rounded-xl p-8 ">
<div>
<Link
to={`/payment/${postData.id}`}
className="py-1 px-2 text-black-600 h-10 ml-24 mt-32 bg-white w-
36 rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600"
>
Buy Now
</Link>
<img
alt=""
className="w-screen object-contain"
src={postData.imageE}
></img>
<h1 className=" ml-24 md:text-5xl sm:text-5xl top-8">
{postData.classE}
</h1>
<h1 className="text-base font-mono ml-24 top-24">
{postData.priceE}
</h1>
</div>
</div>
);
})}
</div>
);
}
export default E;
JSON 文件
[
{
"id": 0,
"class": "A-Class",
"Info": "A is the cheapest one ",
"imageA": "./ModImages/Aclass.jpg",
"textA": "fdsd",
"trefuA": "fdsd",
"optionA": "fdsd"
},
{
"id": 1,
"classE": "E-Class",
"imageE": "./ModImages/Eclass.jpg",
"priceE": "$43,600"
}
]
嘗試這個:
{data.filter(d =>
d.classE &&
d.imageE &&
d.priceE) //FILTER FIRST
.map((postData) => { //THEN MAP
//CODE HERE
})
}
你先過濾數據,然后你 map 它
如果您只想顯示具有classE
、 imageE
和priceE
屬性的對象,則需要過濾掉您不感興趣的對象。
更改此行:
{data.map((postData) => {
至:
{data.filter(d =>
d.hasOwnProperty('classE') &&
d.hasOwnProperty('imageE') &&
d.hasOwnProperty('priceE'))
.map((postData) => {
這將只顯示您想要的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.