在Gatsby中将变量传递到GraphQL查询中

问题描述

我想限制在索引页面获取的帖子数量。当前,页数已硬编码到GraphQL查询中。

query {
    allMarkdownRemark(limit: 5,sort: { fields: [frontmatter___date],order: DESC }) {
      totalCount
      edges {
        node {
          ...
        }
      }
    }
  }

我想用变量的值替换“ 5”。字符串插值不能与graphql函数一起使用,因此我必须使用另一种方法

是否有一种方法可以实现并将变量传递到GatsbyJS中的GraphQL查询中?

解决方法

您只能通过上下文将变量传递给GraphQL查询,因为字符串插值不能以这种方式工作。在page query(而非静态查询)中,您可以使用context对象作为createPage API的参数来传递变量。因此,您需要将此页面创建添加到gatsby-node.js中,并使用类似以下内容的方法:

const limit = 10;

page.forEach(({ node },index) => {
  createPage({
    path: node.fields.slug,component: path.resolve(`./src/pages/index.js`),// your index path
    // values in the context object are passed in as variables to page queries
    context: {
      limit: limit,},})
})

现在,您的context对象中有一个limit值,后面带有所有必需的逻辑(现在它是一个简单的数字,但您可以在其中添加一些计算)。在您的index.js中:

query yourQuery($limit: String) {
    allMarkdownRemark(limit: $limit,sort: { fields: [frontmatter___date],order: DESC }) {
      totalCount
      edges {
        node {
          ...
        }
      }
    }
  }