【发布时间】:2021-02-08 21:30:46
【问题描述】:
我有一个使用 Gatsby-Ghost-Starter 构建的 Gatsby 项目。我正在尝试从 Gatsby 模板文件中的 Ghost 访问博客文章数据。我成功访问了一些数据,但在访问嵌套的 GraphQL 数据时遇到了问题。
使用 Graphiql 界面,这是我试图获取的数据:
query MyQuery {
allGhostPost {
edges {
node {
id
slug
tags {
id
slug
meta_title
name
}
}
}
}
}
这是我的查询在我的 Gatsby 模板中的样子:
export const pageQuery = graphql`
query GhostPostQuery($limit: Int!, $skip: Int!) {
allGhostPost(
sort: { order: DESC, fields: [published_at] },
limit: $limit,
skip: $skip
) {
edges {
node {
...GhostPostFields
}
}
}
}
`
这是我的 Gatsby 模板组件:
const Blog = ({ data, location, pageContext }) => {
const posts = data.allGhostPost.edges
const { pageNumber } = pageContext
const { humanPageNumber } = pageContext
const { numberOfPages } = pageContext
// Dot notation here results in an error, how can I access the name property?
const id = data.allGhostPost.edges.node.tags.name
return (
<React.Fragment>
<MetaData location={location} />
<Layout>
<div className={styles.container}>
<section className={styles.postFeed}>
{posts.map(({ node }) => (
// The tag below includes the markup for each post - components/common/PostCard.js
<PostCard key={node.id} post={node} />
))}
</section>
<Pagination pageContext={pageContext} />
</div>
</Layout>
</React.Fragment>
);
};
如何访问嵌套在边/节点对象中的数据?我的 GraphQL 查询是否不正确,或者我尝试使用点表示法访问它的方式存在问题?
例如,如何检索name 或meta_title?
【问题讨论】:
-
console.log 一步一步......可能是“链”中的数组......我猜
const id = data.allGhostPost.edges[0].node.tags[0].name? -
这成功了。更改边数组索引允许我获取标签名称,即 const id = data.allGhostPost.edges[1].node.tags[0].name, const id = data.allGhostPost.edges[2].node.tags[ 0].name 等...谢谢。
-
...如果您在“主循环”之外需要它...。为什么不直接将
node.tags传递给<PostCard />(使用props.tags.map()在内部呈现标签)?跨度>
标签: reactjs graphql gatsby graphiql