【问题标题】:Gatsby and GraphQL: Accessing data in a template pageGatsby 和 GraphQL:访问模板页面中的数据
【发布时间】: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 查询是否不正确,或者我尝试使用点表示法访问它的方式存在问题?

例如,如何检索namemeta_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 传递给&lt;PostCard /&gt;(使用props.tags.map() 在内部呈现标签)?跨度>

标签: reactjs graphql gatsby graphiql


【解决方案1】:

我有点不明白你在问什么。您有一个posts 循环,其中存储了所有信息。只需通过以下方式访问它:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2019-06-22
    • 2012-05-19
    • 2021-02-11
    • 2019-11-11
    • 2011-04-20
    • 2020-04-01
    相关资源
    最近更新 更多