我正在建立一个带产品的博客,每个产品属于几个类别。您可以单击某个类别,它将转到仅显示具有该类别的产品的页面。
现在,我正在每个“类别页面”上获取所有产品,并使用JS过滤产品,但我只想从一开始就加载我需要的数据。
问题是我应该过滤的变量是我从location.pathname计算的变量; (我从代码段中删除了很多不相关的代码)
如何找到允许我向此查询添加另一个过滤器的语法,该过滤器使用此模板组件中的“category”变量?
render() {
const { classes } = this.props
const posts = get(this, 'props.data.allContentfulBlog.edges')
const edges = this.props.data.allContentfulBlog.edges
const category = location.pathname
return (
<div className={classes.container}>
</div>
)
}
query categoryPostQuery {
allContentfulBlog(
filter: { node_locale: { eq: "en-US" } }
sort: { fields: [date], order: DESC }
) {
edges {
node {
id
categories
date(formatString: "DD MMMM, YYYY")
slug
}
}
}
}
我应该进入类别字段,这是一个数组,并检查它是否包含“类别”变量。
这可以使用Gatsby的query variables来完成:
query categoryPostQuery($category: String) {
allContentfulBlog(
filter: { node_locale: { eq: "en-US" }, categories: { in: [$category] } }
sort: { fields: [date], order: DESC }
) {
edges {
node {
id
categories
date(formatString: "DD MMMM, YYYY")
slug
}
}
}
}
并且可以使用category
context
中的gatsby-node.js
选项设置createPages变量:
createPage({
path,
component: categoryTemplate,
// If you have a layout component at src/layouts/blog-layout.js
layout: `blog-layout`,
context: {
category: 'games'
},
})