【问题标题】:Implement filter options in Gatsby在 Gatsby 中实现过滤器选项
【发布时间】:2019-07-08 15:29:59
【问题描述】:

我对 Gatsby 和 React 还很陌生,我找不到问题的答案。 我希望能够在我的网站主页上设置过滤选项,允许用户仅显示与该过滤器相关的内容。

假设我的帖子是食谱,它们按类型分类:主食、小吃和甜点。 我想要一个过滤器,可以是按钮,也可以是下拉列表,没有关系,当用户选择它时,我将只显示相关的项目。理想情况下,我将有多个过滤器,大约 4 到 5 个过滤器,用于我的帖子前端的不同属性。

据我了解,我无法用 graphql 做任何事情,因为构建后我无法再访问它,所以我正在向更有经验的开发人员寻求一些建议。

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    如果您有一小部分帖子,我认为您可以创建一个搜索组件来获取所有帖子,然后使用js-searchflexsearch 之类的东西来索引它们。

    在非页面组件中(不在src/pages文件夹中),您可以使用StaticQuery获取所有帖子的信息。

    假设你有这个 graphql 查询结果:

    data: {
      allMarkdownRemark: {
        edges: [{
          node: {
            id: '1234-1233...',
            fields: {
              slug: '/hello/'
            },
            frontmatter: {
              title: 'hello',
              tags: [ 'go', 'js' ]
            }
          }
        }, {
          node: {
            id: ...
          }
        }]
      }
    }
    
    

    然后您可以使用 js-search 来索引和搜索帖子:

    const posts = data.allMarkdownRemark.edges.map(({ node }) => node) // unwrap edges
    
    const postIndex = new JsSearch.Search('id')
    postIndex.addIndex(['frontmatter', 'tags']) // index node.frontmatter.tags
    postIndex.addIndex(['frontmatter', 'title'])
    postIndex.addDocuments(posts) // add data to array
    
    const results = postIndex.search('go')
    console.log(results) // [{ id: '1234-1233...', frontmatter: { title: 'hello', tags: [ 'go', 'js' ]}}]
    
    

    然后您可以将此结果存储在组件的状态中,并将结果呈现为帖子。


    盖茨比的文档也有一个 guide 用于向您的网站添加搜索,但我认为 js-search 部分有点压倒性。

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多