Reactjs Gatsby和GraphQL:访问模板页面中的数据
我有一个盖茨比项目,由盖茨比幽灵启动程序构建。我试图访问盖茨比模板文件中Ghost的博客文章数据。我成功地访问了一些数据,但在访问嵌套的GraphQL数据时遇到了问题 使用Graphiql接口,这是我试图获取的数据:Reactjs Gatsby和GraphQL:访问模板页面中的数据,reactjs,graphql,gatsby,graphiql,Reactjs,Graphql,Gatsby,Graphiql,我有一个盖茨比项目,由盖茨比幽灵启动程序构建。我试图访问盖茨比模板文件中Ghost的博客文章数据。我成功地访问了一些数据,但在访问嵌套的GraphQL数据时遇到了问题 使用Graphiql接口,这是我试图获取的数据: query MyQuery { allGhostPost { edges { node { id slug tags { id slug meta_t
query MyQuery {
allGhostPost {
edges {
node {
id
slug
tags {
id
slug
meta_title
name
}
}
}
}
}
以下是我在盖茨比模板中的查询:
export const pageQuery = graphql`
query GhostPostQuery($limit: Int!, $skip: Int!) {
allGhostPost(
sort: { order: DESC, fields: [published_at] },
limit: $limit,
skip: $skip
) {
edges {
node {
...GhostPostFields
}
}
}
}
`
这是我的盖茨比模板组件:
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>
);
};
constblog=({data,location,pageContext})=>{
const posts=data.allGhostPost.edges
常量{pageNumber}=pageContext
常量{humanPageNumber}=pageContext
常量{numberOfPages}=pageContext
//此处的点表示法会导致错误,如何访问name属性?
const id=data.allGhostPost.edges.node.tags.name
返回(
{posts.map({node})=>(
//下面的标记包括每个post-components/common/postcoard.js的标记
))}
);
};
如何访问嵌套在边/节点对象中的数据?我的GraphQL查询是否不正确,或者我如何尝试使用点表示法访问它是否存在问题
例如,我如何检索
名称
或元标题
?我有点不明白你在问什么。您有一个posts
循环,其中存储了所有信息。只需通过以下方式访问:
{posts.map(({ node }, index) => {
console.log('tag name:', node.tags[index].name)
return <PostCard key={node.id} post={node} />
})}
{posts.map({node},index)=>{
console.log('tag name:',node.tags[index].name)
返回
})}
只需一步一步地访问
帖子中的嵌套属性
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等。。。非常感谢。如果你需要它在“主循环”之外。。。。为什么不直接将节点.tags
传递到
(例如,使用props.tags.map()
呈现内部标记)?