【发布时间】:2023-03-24 18:50:01
【问题描述】:
如何呈现来自 Contentful 的 References 字段类型的数据?我可以在 graphql 中查询数据,甚至可以使用它来过滤我网站上的帖子;
query TestQuery {
allContentfulPost {
edges {
node {
categories {
title
slug
}
}
}
}
}
但是当我尝试渲染它以显示在页面中时,它会显示空白 div。但是,我能够呈现所有其他字段类型,只有 References 字段不起作用。
简单的测试代码:
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from "../components/Layout.js"
const TestPage = () => {
const data = useStaticQuery(graphql`
query TestQuery {
allContentfulPost {
edges {
node {
categories {
title
slug
}
}
}
}
}
`)
return (
<Layout>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<div key={node.slug}>
{node.categories.title}
Reference fields should be here but their not ????
</div>
)
})}
</Layout>
)
}
export default TestPage
//
更新:
我已经按照下面 Ferran 的建议对 GraphQL 片段进行了一些试验和错误,我能够查看 localhost:8000/___graphql 中的数据;
query TestQuery {
allContentfulPost {
edges {
node {
categories {
... on ContentfulCategory {
title
slug
}
}
}
}
}
}
但是,呈现的 div 仍然是空的。我是否需要在返回函数中更改数据源“{node.categories.title}”的路径才能使其工作?我是否可能需要在“节点”和“类别”之间添加一些内容以引用在 graphql 查询中添加的“... on ContentfulCategory”?如果是这样,我应该怎么写?我试过“{node.oncontentfulcategory.categories.title}”,但没有奏效。再次感谢
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from "../components/Layout.js"
const TestPage = () => {
const data = useStaticQuery(graphql`
query TestQuery {
allContentfulPost {
edges {
node {
categories {
... on ContentfulCategory {
title
slug
}
}
}
}
}
}
`)
return (
<Layout>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<div key={node.slug}>
{node.categories.title}
What path should I now use for the data source in the line above?
</div>
)
})}
</Layout>
)
}
export default TestPage
【问题讨论】:
标签: reactjs graphql gatsby contentful