Gatsby和GraphQL:访问模板页面中的数据

问题描述

我有一个使用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查询不正确吗?或者我尝试用点表示法访问它的方式有问题吗?

例如,如何检索nameMeta_title

解决方法

我对您的要求有些困惑。您有一个posts循环,其中存储了所有信息。只需使用以下命令即可访问它:

{posts.map(({ node },index) => {
   console.log('tag name:',node.tags[index].name)
   return <PostCard key={node.id} post={node} />
})}

只需访问posts中的嵌套属性即可。