如何只渲染对象数组中的第一个图像



我有一个包含产品详细信息的对象数组。在对象上,有一个对象属性的images数组,其中所有id为的图像都在那里我试图只渲染该对象数组中的第一个图像我曾尝试设置0个索引以仅渲染第一个对象,但我遇到了一个错误。

我的数据库:

[
{
_id: "asdasdds",
title: "Title",
reg_price: string
images: [
{
id: "a1e73da66ddb9191984e3128b0df78af"
src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
},
{
id: "a1e73da66ddb9191984e3128b0df78af"
src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
},
]
},
{
_id: "asdasdds",
title: "Title",
reg_price: string
images: [
{
id: "a1e73da66ddb9191984e3128b0df78af"
src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
},
{
id: "a1e73da66ddb9191984e3128b0df78af"
src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
},
{
id: "a1e73da66ddb9191984e3128b0df78af"
src: "https://res.cloudinary.com/df8velsbs/image/upload/v1645508032/uts3xxi6wbckrjzjsrgx.png"
},
]
}
]

这是我的代码:当我设置0索引product.images[0]时,我得到的映射不存在错误。

{
products.map(product => {
return <tr>
<td className="px-5 py-5 border-b border-gray-200 bg-white text-sm">
<div className="flex items-center">
<div className="flex-shrink-0 w-10 h-10">
{                  
product.images[0].map(({ src }) => <img className="w-full h-full rounded-full"
src={src}
alt="" />)
}
</div>
</div>

您根本不需要映射。只需直接引用0索引元素的src属性

{products.map(product => (
<tr>
<td className="px-5 py-5 border-b border-gray-200 bg-white text-sm">
<div className="flex items-center">
<div className="flex-shrink-0 w-10 h-10">
<img
alt=""
className="w-full h-full rounded-full"
src={product.images[0]?.src ?? "some-placeholder.png"}
/>
</div>
</div>
</td>
</tr>
)}

最新更新