[英]React map through multiple arrays of objects and display components on site?
I'm trying to create card components and map through my data file to display them, which I managed to do with one array object data file.我正在尝试创建卡片组件并映射我的数据文件以显示它们,我设法用一个数组对象数据文件来完成。 But my problem occurs if I want to reuse the card component with a new array data file, I can't seem to get the data.但是如果我想用新的数组数据文件重用卡片组件,我的问题就会出现,我似乎无法获取数据。
So data example所以数据示例
export const data1 = [
{
title: 'first',
desc: 'first desc,
img: 'image-1.jpg'
},
{
title: 'second',
desc: 'second desc,
img: 'image-2.jpg'
},
]
So if I only have one data array, I just map through it like this所以如果我只有一个数据数组,我就这样映射
{data1.map((data, index) => {
return (
<Title>{data.title}</Title>
<Desc>{data.desc}</Desc>
<Img src={data.img} />
)
})
Then if I wanna display this card component, I would just add it to my page然后如果我想显示这个卡片组件,我会把它添加到我的页面
<CardComponent />
But now if I wanna reuse this component and just switch out the data, I can't map through it properly because it's only mapping through the data1 array.但是现在如果我想重用这个组件并只切换出数据,我不能正确地映射它,因为它只映射到 data1 数组。
So if I make another array所以如果我制作另一个数组
export const dataTwo = [
{
title: 'third',
desc: 'third desc,
img: 'image-3.jpg'
},
{
title: 'fourth',
desc: 'fourth desc,
img: 'image-4.jpg'
},
]
Now I can't reuse my component because the map() is only targeting data1.map and not dataTwo.map现在我不能重用我的组件,因为 map() 只针对 data1.map 而不是 dataTwo.map
So I'm not sure exactly how I'd create essentially a new Card component所以我不确定我将如何创建一个新的 Card 组件
Ideally, I'd want this result理想情况下,我想要这个结果
<Navbar />
<CardComponent {...data1} />
<MainSection>
<CardComponent {...dataTwo} />
<Footer />
But the issue is I am mapping through the values instead of just getting data from a regular object, so this method doesn't work.但问题是我正在映射值,而不仅仅是从常规对象中获取数据,因此此方法不起作用。
Any idea how I would implement this?知道我将如何实现这一点吗?
Simply pass the arrays as a prop to CardComponent
, such as a data
prop.只需将数组作为道具传递给CardComponent
,例如data
道具。
<CardComponent data={data1} />
...
<CardComponent data={dataTwo} />
And map the passed data
prop in CardComponent
.并在CardComponent
映射传递的data
道具。 Remember that the mapping needs to return everything wrapped in a single node (ie div
, Fragment
, etc..) and should have an attached react key.请记住,映射需要返回包含在单个节点中的所有内容(即div
、 Fragment
等),并且应该有一个附加的反应键。
Example例子
const CardComponent = ({ data }) => {
return (
<>
{data.map((data, index) => {
return (
<Fragment key={index}>
<Title>{data.title}</Title>
<Desc>{data.desc}</Desc>
<Img src={data.img} />
</Fragment>
);
})}
</>
);
};
If you have multiple arrays that you want to be displayed, you can flatten them together into one when calling the component, eg:如果您有多个要显示的数组,可以在调用组件时将它们拼合为一个,例如:
<CardComponent data={data1.concat(dataTwo)} />
props.data.map((item) => (
<Title>{item.title}</Title>
<Desc>{item.desc}</Desc>
<Img src={item.img} />
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.