在GatsbyJS中筛选GraphQL查询中的项目时遇到问题。我本以为可以在createPage
的context
部分(如下面的currentDate
和minusFiveDays
)创建键-值对,然后将它们用作页面组件中的参数,但似乎行不通。
在gatsby-node.js
中
const currentDate = moment().format('YYYY-MM-DD');
const minusFiveDays = moment()
.subtract(5, 'days')
.format('YYYY-MM-DD');
console.log('DATE', minusFiveDays); // this logs correctly
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.frontmatter.slug,
component: someContentTypeTemplate,
context: {
// Can the names passed in here be accessed in
// graphql queries, prefixed with a dollar sign?
currentDate: currentDate,
minusFiveDays: minusFiveDays,
},
});
});
在src/pages/someContentType.js
文件中:
// TODO: this query doesn't work. No matter what condition I try to use
// for $minusFiveDays, it doesn't affect the output. The query does work in
// graphiql when I hard-code a string there like "2018-11-01".
export const pageQuery = graphql`
query($minusFiveDays: Date) { // this is the key from the file above
allMarkdownRemark(
filter: {
frontmatter: {
content_type: { eq: "some_content_type" }
start_date: { ne: null, gte: $minusFiveDays }
}
}
sort: { order: ASC, fields: [frontmatter___start_date] }
) {
edges {
node {
id
frontmatter {
created_at
slug
title
start_date(formatString: "DD MMMM YYYY")
end_date
}
}
}
}
}
`;
即使我像这样硬编码它,它也不能工作,所以上下文似乎不会传递到组件的GraphQL查询中:
context: {
currentDate: currentDate,
minusFiveDays: "2018-11-01",
},
这在GraphiQL中是有效的:
{
allMarkdownRemark(filter: {frontmatter: {content_type: {eq: "some_content_type"}, start_date: {ne: null, gte: "2018-11-01"}}}, sort: {order: DESC, fields: [frontmatter___start_date]}) {
edges {
node {
id
frontmatter {
created_at
slug
title
start_date(formatString: "DD MMMM YYYY")
end_date
}
}
}
}
}
我认为我的语法一定是错误的,但我是GraphQL和Gatsby的新手,并且没有错误消息。EDIT:当我将Date
更改为Date!
:Variable "$minusFiveDays" of required type "Date!" was not provided.
时出现错误消息
发布于 2019-06-24 20:16:43
我认为问题在于您的模板在src/pages
目录中。
src/pages
中的*.js
文件将自动构建到页面中,包括您的模板someContentType.js
。这意味着Gatsby会在您在gatsby-node.js
中进行的自定义createPage
调用之上自动为您生成此页面。
但是,当Gatsby自动生成此页面时,它并不知道您通过createPage
传入的上下文。这就是它不起作用的原因。
将您的模板移出src/pages
可能会解决您的问题。
发布于 2019-06-06 03:18:48
我认为这可能是因为你从这一行得到的值:
const minusFiveDays = moment().subtract(5, 'days').format('YYYY-MM-DD');
不是Date
类型。从控制台中的一个小试用来看,它似乎是一个字符串。
如果改为:
$minusFiveDays: String!
如果没有看到你的项目,我就不能确定它可能会起作用。
https://stackoverflow.com/questions/56448610
复制相似问题