GatsbyJS按位置路径名筛选查询

问题描述 投票:1回答:1

我正在建立一个带产品的博客,每个产品属于几个类别。您可以单击某个类别,它将转到仅显示具有该类别的产品的页面。

现在,我正在每个“类别页面”上获取所有产品,并使用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              
        }
      }
    }
  }

我应该进入类别字段,这是一个数组,并检查它是否包含“类别”变量。

reactjs graphql gatsby contentful
1个回答
1
投票

这可以使用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'
    },
})
© www.soinside.com 2019 - 2024. All rights reserved.