在Gatsby中将变量传递到GraphQL查询
我想限制在我的索引页上获取的帖子数量。目前,页面数已硬编码到GraphQL查询中在Gatsby中将变量传递到GraphQL查询,graphql,gatsby,Graphql,Gatsby,我想限制在我的索引页上获取的帖子数量。目前,页面数已硬编码到GraphQL查询中 query { allMarkdownRemark(limit: 5, sort: { fields: [frontmatter___date], order: DESC }) { totalCount edges { node { ... } } } } 我想用变量的值替换“5”。字符串插值不能与grap
query {
allMarkdownRemark(limit: 5, sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
...
}
}
}
}
我想用变量的值替换“5”。字符串插值不能与graphql
函数一起使用,因此我必须使用另一种方法
有没有办法在GatsbyJS中将变量传递到GraphQL查询中?您只能通过上下文将变量传递到GraphQL查询,因为字符串插值不能以这种方式工作。在(而不是静态查询)中,可以使用
上下文
对象作为的参数传递变量。因此,您需要将此页面创建添加到您的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,
},
})
})
现在,您的上下文中有一个limit
值,后面有所有需要的逻辑(现在是一个简单的数字,但您可以在其中添加一些计算)。在您的index.js
中:
query yourQuery($limit: String) {
allMarkdownRemark(limit: $limit, sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
...
}
}
}
}