我在嘗試訪問包含類別數組的 Post 數組時遇到問題。因此,如果我 console.log 數據,我會看到如下內容:
{
posts: [
{
_createdAt: '2021-10-23T05:02:26Z',
_type: 'post',
_updatedAt: '2021-10-23T23:28:09Z',
body: [Array],
categories: [Array], <<<<-- this is the one I need to access
mainImage: [Object],
publishedAt: '2021-10-23T18:30:00.000Z',
slug: [Object],
title: 'Post Name title goes here'
}
.
.
.
]
}
我需要訪問 Post Array 中的類別 Array,但是我很難訪問它。我目前嘗試過這樣的事情:
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
{posts.map(
({
_id,
title = "",
slug = "",
_createdAt = "",
mainImage = "",
categories = "",
}) =>
slug && (
<div className="shadow-lg rounded-lg bg-white pb-5" key={_id}>
<div className="px-6 py-4 text-left">
<div className="flex flex-row mt-4 items-center">
{categories && (
<ul className="inline-flex my-3" style={{ listStyle: "none" }}>
{categories.map((category) => (
<li key={category}>
<span
className="mx-2
items-center
justify-center
px-2
py-1
text-xs
font-bold"
>
{category}
</span>
</li>
))}
</ul>
)}
</div>
</div>
</div>
)
)}
</div>;
當我這樣做時,我收到以下錯誤:
對像作為 React 子對象無效(找到:帶有鍵 {_key, _ref, _type} 的對象)。如果您打算渲染一組子項,請改用數組。
我什至嘗試做這樣的事情:
{posts.categories.map((category) => (
<li key={category}>
<span
className="mx-2
items-center
justify-center
px-2
py-1
text-xs
font-bold"
>
{category}
</span>
</li>
));
}
但仍然沒有運氣。關於我做錯了什麼的任何想法?謝謝!
從錯誤看來,它categories
是一個引用數組。您需要解析 GROQ 查詢中的引用(類似於"categories": categories[]->
),然後在前端,您需要使用每個對象的屬性category
(在映射時創建categories
)而不是整個對象本身。你會想像categories
你所做的那樣進行映射,但在映射回調函數中,你永遠不會直接引用整個對象。
而不是:
{posts.categories.map((category) => (
<li key={category}>
<span>
{category}
</span>
</li>
));
}
你會想要做類似的事情(假設一個text
屬性存在):
{posts.categories.map((category) => (
<li key={category._id}>
<span>
{category.text}
</span>
</li>
));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句