GatsbyJS按位置路径名过滤查询

时间:2018-09-02 11:17:57

标签: reactjs graphql gatsby contentful

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

现在,我将在每个“类别页面”上获得所有产品,并使用JS来过滤产品,但我只想从一开始就加载所需的数据。

问题是我要过滤的变量是我根据location.pathname计算的变量; (我从代码段中删除了许多不相关的代码)

我如何找到一种语法,该语法允许我使用此模板组件中的“类别”变量向该查询添加另一个过滤器?

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              
        }
      }
    }
  }

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

1 个答案:

答案 0 :(得分:1)

这可以使用盖茨比的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 createPages中的context选项设置gatsby-node.js变量:

createPage({
    path,
    component: categoryTemplate,
    // If you have a layout component at src/layouts/blog-layout.js
    layout: `blog-layout`,
    context: {
       category: 'games'
    },
})
相关问题