![](/img/trans.png)
[英]Is it possible to use Graphql query with React Class component?
[英]Using GraphQL context variable in React component GraphQL query
我正在嘗試在我的React組件中構造一個GraphQL查詢,我需要限制返回的結果數量。 我正在gatsby-node.js文件的“ createPage”函數的“ context”屬性內設置極限值。
在我的React組件中,可以看到limit屬性是通過“ props.pageContext.limit”傳遞的。 我需要使用此極限值並將其傳遞到我的React組件底部的GraphQL查詢
下面是我嘗試過的方法,但是它不起作用,如果我從查詢中忽略了限值,則它將返回所有結果。
//gatsby-node.js
...
const postsPerPage = 3;
createPage({
path: node.fields.slug,
component: path.resolve("./src/templates/page.js"),
context: {
limit: postsPerPage,
slug: node.fields.slug,
category: node.frontmatter.category
}
});
...
//my-component.js
...
export const query = graphql`
query($limit: Int!, $slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
category
}
}
allMarkdownRemark(limit: $limit) {
edges {
node {
frontmatter {
title
excerpt
}
fields {
slug
}
}
}
}
}
`
僅當從頁面模板組件中導出GraphQL查詢時,它們才會使用指定的參數自動執行。 在您的情況下,如果此查詢存在於./src/templates/page.js
,則將執行該查詢。 然后,您可以通過prop將數據傳遞給子組件。
由於Gatsby不會自動在非頁面組件中執行查詢,因此您的查詢當前被忽略。 您可以使用StaticQuery
組件或useStaticQuery
掛鈎從子組件中查詢數據。 但是,顧名思義,這些是靜態查詢,不接受任何參數。
如果您確實希望在子組件中描述查詢,則還可以查看“ Fragments
,這是將大型查詢分為多個可重用部分的一種方式。
有用的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.