【问题标题】:Multiple queries in a component for GatsbyGatsby 组件中的多个查询
【发布时间】:2021-09-06 09:36:20
【问题描述】:

我使用 Gatsby 来创建页面,然后在 createPage 方法中我引用页面的特定组件

createPage({
  path: node.path.alias,
  component: path.resolve(`./src/layouts/custom-page/custom-page.js`),
  context: {
    articleId: node.id,
    authorId: node.relationships.field_author.id
  },
})

在布局内 (custom-page.js) 我正在尝试执行 2 个查询,但它对我不起作用。当我在 GraphiQL 中测试这个查询时,它工作正常。

export const query = graphql `
    query ($articleId: String!, $authorId: String!) {
      article: nodeArticle(id: {eq: $articleId}) {
        title
        body {
          value
        }
        path {
          alias
        }
      }    
      author: nodePerson(id: {eq: $authorId}) {
        title       
        path {
          alias
        }
      }      
    }
`;

在我的组件中,我希望能够使用data.author.titledata.article.title 访问数据。

在 Gatsby 中可以做到这一点吗?

【问题讨论】:

    标签: graphql gatsby


    【解决方案1】:

    您的查询似乎有点错误或查询中缺少某些内容。

    查询应该是这样的。

    export const query = graphql `
        query Articles($articleId: String!, $authorId: String!) {
          article: nodeArticle(id: {eq: $articleId}) {
            title
            body {
              value
            }
            path {
              alias
            }
          }    
          author: nodePerson(id: {eq: $authorId}) {
            title       
            path {
              alias
            }
          }      
        }
    `;
    

    最好使用包graphql-tag

    您的查询将如下所示。

    import gql from 'graphql-tag';
    
    export const query = gql`
        query Articles($articleId: String!, $authorId: String!) {
          article: nodeArticle(id: {eq: $articleId}) {
            title
            body {
              value
            }
            path {
              alias
            }
          }    
          author: nodePerson(id: {eq: $authorId}) {
            title       
            path {
              alias
            }
          }      
        }
    `;
    

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 2021-02-05
      • 2021-07-16
      • 2018-06-16
      • 2019-05-18
      • 2021-05-29
      • 2019-06-12
      • 2023-04-06
      • 2019-12-21
      相关资源
      最近更新 更多