访问MongoDB集合中的嵌套数组



这几天我一直在绞尽脑汁,但没有任何进展。

我有一个使用MERN堆栈的项目,我正试图从我的数据库访问嵌套数组。

我的数据结构是这样的:

const Products = [
{
name: 'Air Zoom Pegasus 37',
brand: 'Nike',
category: 'running',
material: 'Textile & Synthetic Upper/Synthetic sole',
description: 'Hit a new PB in these mens Air Zoom Pegasus 37 trainers from Nike. In an Off Noir colourway with hits of Blue Fury and Bright Crimson, these runners have lightweight mesh upper for a breathable feel. They feature a secure lace up fastening and are sat on a soft foam midsole for long-lasting cushioning and maximum responsiveness. With Nikes Air Zoom unit at the forefront for a smooth ride, these trainers are finished with a grippy rubber tread and the iconic Swoosh logo to the sidewalls.',
price: 105,
sizes: [
{ size: '6', countInStock: 10 },
{ size: '7', countInStock: 10 },
{ size: '8', countInStock: 10 },
{ size: '9', countInStock: 10 },
{ size: '10', countInStock: 10 },
{ size: '11', countInStock: 10 },
{ size: '12', countInStock: 10 }
],
image1: '/images/nike_pegasus37_1.jpeg',
image2: '/images/nike_pegasus37_2.jpeg',
image3: '/images/nike_pegasus37_3.jpeg',
image4: '/images/nike_pegasus37_4.jpeg',
image5: '/images/nike_pegasus37_5.jpeg',
image6: '/images/nike_pegasus37_6.jpeg',
rating: 0,
numReviews: 0,
tags: 'nike, adidas, running, trainers, 5k, new, style',
},
]

我似乎无法访问' size '数组中的嵌套对象。所有的属性都在使用Redux的状态下返回,我可以看到数据有效载荷在我的Redux Devtools on Chrome上从这个BSON列表返回所有项目。

我正在使用Axios从MongoDB集合检索此数据,并使用Redux使用调度和选择器来管理我的状态。其他的都可以。我可以获取所有其他信息,所以我知道这不是后端问题,但我似乎不知道如何映射数组

任何帮助都将非常感激。

谢谢,利亚姆。

要在react中映射数组,可以这样做

Component start......
return {
<div>
{
// First map over your Products
// note the ? is there to prevent it from crashing if Products is not defined
Products?.map(product => {
return <>
<p>{product.name}</p>

//then map over this products sizes
<div>

{product?.sizes.map(size => {
return <p>{size.size} - {size.countInStock}</p>
})}
</div>
</>
})
}
</div>
}

最新更新