[英]Passing Variables into GraphQL Query in Gatsby
我想限制在我的索引頁面上獲取的帖子數量。 目前,頁數被硬編碼到 GraphQL 查詢中。
query {
allMarkdownRemark(limit: 5, sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
...
}
}
}
}
我想用變量的值替換“5”。 字符串插值不適用於graphql
function,所以我必須使用另一種方法。
有沒有辦法實現這一點並將變量傳遞到 GatsbyJS 中的 GraphQL 查詢中?
您只能通過上下文將變量傳遞給 GraphQL 查詢,因為字符串插值不能以這種方式工作。 在頁面查詢(而不是 static 查詢)中,您可以使用context
object 作為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
object 中有一個limit
值,其中包含所有必需的邏輯(現在它是一個簡單的數字,但您可以在那里添加一些計算)。 在您的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.