我有一組包含產品詳細資訊的物件。在物件上,有一個物件屬性的影像陣列,其中所有具有 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>
uj5u.com熱心網友回復:
你根本不需要映射。直接參考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>
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436823.html
標籤:javascript 数组 反应 javascript 对象 反应打字稿
下一篇:將每個物件的陣列設定為x索引元素
