简体   繁体   English

将变量传递给 Gatsby 中的 GraphQL 查询

[英]Passing Variables into GraphQL Query in Gatsby

I want to limit the number of posts fetched on my index page.我想限制在我的索引页面上获取的帖子数量。 Currently, the number of pages is hard-coded into the GraphQL query.目前,页数被硬编码到 GraphQL 查询中。

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

I want to replace "5" with the value of a variable.我想用变量的值替换“5”。 String interpolation will not work with the graphql function, so I have to use another method.字符串插值不适用于graphql function,所以我必须使用另一种方法。

Is there a way to achieve this and pass variables into a GraphQL query in GatsbyJS?有没有办法实现这一点并将变量传递到 GatsbyJS 中的 GraphQL 查询中?

You can only pass variables to GraphQL query via context since string interpolation doesn't work in that way.您只能通过上下文将变量传递给 GraphQL 查询,因为字符串插值不能以这种方式工作。 In page query (rather than static queries) you can pass a variable using the context object as an argument of createPage API .页面查询(而不是 static 查询)中,您可以使用context object 作为createPage API的参数来传递变量。 So, you'll need to add this page creation to your gatsby-node.js and use something like:因此,您需要将此页面创建添加到您的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,
    },
  })
})

Now, you have in your context object a limit value with all the required logic behind (now it's a simple number but you can add there some calculations).现在,您在context object 中有一个limit值,其中包含所有必需的逻辑(现在它是一个简单的数字,但您可以在那里添加一些计算)。 In your index.js :在您的index.js中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM