簡體   English   中英

Gatsby 組件中的多個 graphql 查詢

[英]Multiple graphql queries in Gatsby component

我需要在一個組件和gatsby-node.js文件中運行多個 graphQL 查詢。 (因為 Prismic 每個答案限制為 20 個條目......)

我嘗試了以下方法,只是想看看我是否可以在默認的 function 中創建 graphql 循環:

export default () => {
  async function allPosts() {
    let data

    await graphql(`
      query allDitherImages {
        prismic {
          allProjects(sortBy: meta_firstPublicationDate_DESC) {
            totalCount
            pageInfo {
              startCursor
              endCursor
              hasNextPage
              hasPreviousPage
            }
            edges {
              node {
                cover_image
                cover_imageSharp {
                  name
                }
              }
            }
          }
        }
      }
    `).then(initialRes => {
      data = initialRes
    })

    return data
  }

  allPosts().then(result => {
    console.log(result)
  })
  return null
}

但是后來 Gatsby 告訴我Gatsby related 'graphql' calls are supposed to only be evaluated at compile time, and then compiled away. Unfortunately, something went wrong and the query was left in the compiled code. Gatsby related 'graphql' calls are supposed to only be evaluated at compile time, and then compiled away. Unfortunately, something went wrong and the query was left in the compiled code.

如何運行多個 graphql 查詢?

提前謝謝你:)邁克爾

gatsby-source-prismic-graphql package 將為您的所有 Prismic 項目(不僅僅是前 20 個)創建頁面,因為它會遍歷引擎蓋下的所有項目,所以如果您正在尋找,我建議您考慮使用它為所有這些項目生成頁面。

但是,如果您需要獲取所有項目並將它們傳遞到 pageContext 或其他內容中,則需要自己在 gatsby-node 中進行遞歸。

在 gatsby-node 中,定義查詢后,您可以使用類似這樣的方法來迭代結果並推送到數組。

let documents = [];
async function getAllDocumentsRecursively (query, prop, endCursor = '') {
  const results = await graphql(query, { after: endCursor })
  const hasNextPage = results.data.prismic[prop].pageInfo.hasNextPage
  endCursor = results.data.prismic[prop].pageInfo.endCursor

  results.data.prismic[prop].edges.forEach(({node}) => {
    documents.push(node)
  });

  if (hasNextPage) {
    await getAllDocumentsRecursively(query, 'allDitherImages ', endCursor)
  }
}
await getAllDocumentsRecursively(documentsQuery, 'allDitherImages ');

然后在您的 createPage 中,將數組傳遞到上下文中:

createPage({
    path: `/`+ node._meta.uid,
    component: allDitherTempate,
    context: {
      documents: documents
    }
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM