当我点击一篇文章或我网站上其他地方的标签时,我想创建动态页面。
我使用Next.js、SSG,并通过以下GraphQL查询从Contentful获取包含标签的文章:
export async function getArticles() {
const articlesQuery = gql`
{
articleCollection(order: date_DESC) {
items {
title
slug
excerpt
date
contentfulMetadata {
tags {
name
id
}
}
featuredImage {
title
url
width
height
}
author {
name
photo {
fileName
url
width
height
}
title
twitterProfile
linkedInProfile
slug
}
}
}
}
`;
return graphQLClient.request(articlesQuery);
}export async function getArticle(slug) {
const articleQuery = gql`
query getArticle($slug: String!) {
articleCollection(limit: 1, where: { slug: $slug }) {
items {
title
slug
excerpt
date
contentfulMetadata {
tags {
name
id
}
}
featuredImage {
title
url
width
height
}
author {
name
photo {
fileName
url
width
height
}
title
twitterProfile
linkedInProfile
slug
}
content {
json
links {
entries {
block {
sys {
id
}
__typename
... on VideoEmbed {
title
embedUrl
}
... on CodeBlock {
description
language
code
}
}
}
assets {
block {
sys {
id
}
url
title
width
height
}
}
}
}
}
}
}
`;
return graphQLClient.request(articleQuery, {
slug,
});
}contentfulMetadata是标签的来源:
contentfulMetadata {
tags {
name
id
}
}这是我的id.jsx文件:
import { getArticles, getArticle } from "@utils/contentful";
export async function getStaticPaths() {
const data = await getArticles();
return {
paths: data.articleCollection.items.map((article) => ({
params: { id: article.contentfulMetadata.tags[0].id },
})),
fallback: false,
};
}
export async function getStaticProps(context) {
const data = await getArticle(context.params.id);
return {
props: { article: data.articleCollection.items[0] },
};
}
export default function TagPage({ article }) {
return (
<div>
<h1>{article.contentfulMetadata.tags.id}</h1>
</div>
);
}我得到以下错误:Error: Error serializing `.article` returned from `getStaticProps` in "/tags/[id]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
当在getStaticPaths函数中使用console.log(data.articleCollection.items.contentfulMetadata.tags.id);或console.log(data.articleCollection.items.contentfulMetadata.tags[0].id);时,它会提供以下错误:TypeError: Cannot read property 'tags' of undefined
谁能演示一下如何创建一个动态页面(id.jsx)文件,该文件将标签id显示为标题<h1>以及包含相同标签的所有文章?
发布于 2021-07-26 15:22:00
Contentful DevRel在这里??。
article.contentfulMetadata.tags是一个数组,因为一个条目可以有多个标签。因此,您需要通过article.contentfulMetadata.tags[0].id或article.contentfulMetadata.tags[desired_index].id等访问所需的标记。
下面是一个示例GraphQL查询:
query {
blogPostCollection {
items {
contentfulMetadata {
tags {
id
name
}
}
}
}
}下面是以数组形式包含标记的响应:
"data": {
"blogPostCollection": {
"items": [
{
"contentfulMetadata": {
"tags": [
{
"id": "salmastag",
"name": "Salma s tag"
}
]
}
},
{
"contentfulMetadata": {
"tags": []
}
}
]
}
}
}注意,如果一篇博客文章没有分配任何公共标签(响应中的第二个条目),返回一个空数组,- you可能希望在代码中为此做一些安全检查。
https://stackoverflow.com/questions/68520154
复制相似问题