reactjs - 如何在 React 中从 Contentful 渲染参考字段?
问题描述
如何从 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
解决方案
您需要在查询中添加 GraphQL 片段以访问参考数据。您在Gatsby 文档 (gatsby-source-contentful
) 或其他一些GitHub 线程中有一个糟糕的示例。
该插件将推断您的架构引用并创建适当的节点,允许您在查询中使用它们来检索所需的数据。您应该在 localhost:8000/___graphql 中进行一些试验和错误,以确保您的模型正常工作,否则很难猜测查询应该是什么样子,但它应该是这样的:
const data = useStaticQuery(graphql`
query TestQuery {
allContentfulPost {
edges {
node {
categories {
title
slug
__typename
...on contentfulCategories{
#your category fields
}
}
}
}
}
}
`)
更多参考资料/文章:
推荐阅读
- excel - VBA中如何使用EXCEL“情景分析目标值”
- github - Dependabot 没有找到最新的提交
- linux-kernel - 如何向/从内核模块传递/读取配置数据,例如/etc/file?
- github - 如何使用 Github GUI 恢复到以前的提交?
- python - 如果用户有一些角色 discord.py,我正在尝试做一些事情
- asp.net - Fedex API 集成 - 如何访问退货标签图像?
- regex - 在地址表单中限制邮政信箱地址
- java - 我试图找到两点之间的距离
- excel - 根据范围“F”值插入行后从范围“H”复制一个值
- python - 反映加密的 Access 数据库时出现“无效密码”错误