Gatsby.js 条件查询
Gatsby.js Conditional querying
我想像这样在我的组件中使用条件查询:
export const pageQuery =
DATA_SOURCE === 'strapi'
? graphql`
query AllNews {
allStrapiApiupdates(sort: { order: DESC, fields: [date] }) {
edges {
node {
id
title
description
date(formatString: "DD.MM", locale: "ru")
}
}
}
}
`
: graphql`
query AllNews {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
filter: { frontmatter: { type: { eq: "news" } } }
) {
edges {
node {
id
frontmatter {
title
date(formatString: "DD.MM", locale: "ru")
type
}
html
}
}
}
}
`
但是我得到了错误:
Uncaught (in promise) ReferenceError: graphql is not defined
at Module.eval (D:/Projects/AHML-DWH/api-news-front/src/pages/index.tsx:68)
at eval (D:/Projects/AHML-DWH/api-news-front/src/pages/index.tsx:146)
at Module../src/pages/index.tsx (commons.js:9487)
...
我想这与转译有关。有什么办法吗?
简单的回答是,不,这是不可能的。
Gatsby 从您的模板文件中提取查询并进行特殊处理。它无法使这些查询动态化。理论上,您可以使用 GraphQL directive 实现此目的。但我认为不可能按照您发布的方式在 Gatsby 中执行此操作。
根据我现在的尝试,我会告诉您不能将指令 @include(if:$myBolean)
与 filters、sorts[=21 一起使用=],等等,但你也可以在 gatsby 中使用它们 和字段。
然后,在您的情况下,您可以使用指令执行整个查询,例如
query AllNews($myBolean: Boolean!) {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
filter: { frontmatter: { type: { eq: "news" } } }
) @include(if:$myBoolean) {
edges {
node {
id
frontmatter {
title
date(formatString: "DD.MM", locale: "ru")
type
}
html
}
}
}
}
然后你可以在一个 graphql 调用中添加两个查询,并根据布尔值只执行其中一个
我想像这样在我的组件中使用条件查询:
export const pageQuery =
DATA_SOURCE === 'strapi'
? graphql`
query AllNews {
allStrapiApiupdates(sort: { order: DESC, fields: [date] }) {
edges {
node {
id
title
description
date(formatString: "DD.MM", locale: "ru")
}
}
}
}
`
: graphql`
query AllNews {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
filter: { frontmatter: { type: { eq: "news" } } }
) {
edges {
node {
id
frontmatter {
title
date(formatString: "DD.MM", locale: "ru")
type
}
html
}
}
}
}
`
但是我得到了错误:
Uncaught (in promise) ReferenceError: graphql is not defined at Module.eval (D:/Projects/AHML-DWH/api-news-front/src/pages/index.tsx:68) at eval (D:/Projects/AHML-DWH/api-news-front/src/pages/index.tsx:146) at Module../src/pages/index.tsx (commons.js:9487) ...
我想这与转译有关。有什么办法吗?
简单的回答是,不,这是不可能的。
Gatsby 从您的模板文件中提取查询并进行特殊处理。它无法使这些查询动态化。理论上,您可以使用 GraphQL directive 实现此目的。但我认为不可能按照您发布的方式在 Gatsby 中执行此操作。
根据我现在的尝试,我会告诉您不能将指令 @include(if:$myBolean)
与 filters、sorts[=21 一起使用=],等等,但你也可以在 gatsby 中使用它们 和字段。
然后,在您的情况下,您可以使用指令执行整个查询,例如
query AllNews($myBolean: Boolean!) { allMarkdownRemark( sort: { order: DESC, fields: [frontmatter___date] } filter: { frontmatter: { type: { eq: "news" } } } ) @include(if:$myBoolean) { edges { node { id frontmatter { title date(formatString: "DD.MM", locale: "ru") type } html } } } }
然后你可以在一个 graphql 调用中添加两个查询,并根据布尔值只执行其中一个