所以我现在遇到了一个小问题。所以我有一个从JSON获取数据的组件,我有Link,但显示了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"
}
]发布于 2020-12-27 08:51:19
如果只想显示具有属性classE、imageE和priceE的对象,则需要过滤掉不感兴趣的对象。
更改此行:
{data.map((postData) => {至:
{data.filter(d =>
d.hasOwnProperty('classE') &&
d.hasOwnProperty('imageE') &&
d.hasOwnProperty('priceE'))
.map((postData) => {这将只显示您想要的对象。
发布于 2020-12-27 13:05:20
试试这个:
{data.filter(d =>
d.classE &&
d.imageE &&
d.priceE) //FILTER FIRST
.map((postData) => { //THEN MAP
//CODE HERE
})
}首先过滤数据,然后对其进行映射
https://stackoverflow.com/questions/65461560
复制相似问题