代码之家  ›  专栏  ›  技术社区  ›  Giulia

如何按类别筛选文章以确定分页的确切页数(JS)

  •  0
  • Giulia  · 技术社区  · 6 年前

    在我的gatsbyjs网站中,我对文章进行了分类,并为每个分类创建了一个页面,并根据页面上显示的最大文章数对每个页面进行分页。

    代码如下:

    盖茨比节点.js

    let categories = []
     _.each(result.data.allMarkdownRemark.edges, edge => {
         if (_.get(edge, "node.frontmatter.categories")) {
            categories = categories.concat(edge.node.frontmatter.categories)
            }
        })
    
        const categoryarticles = categories.filter(category =>{
            return category === category
        })
    
        const categoryarticlesPerPage = 6
        const numPages = Math.ceil(categoryarticles.length / categoryarticlesPerPage)
    
        //Creating a PAGINATED page for each category, so that any category page will only display a certain amount of articles (defined in categoryarticlesPerPage)
        Array.from({ length: numPages }).forEach((el, i) => {
            categories.forEach(category => {
                createPage({
                    path: i === 0 ? `/${_.kebabCase(category)}` : `/${_.kebabCase(category)}/${i + 1}`,
                    component: categoryTemplate,
                    context: {
                        category,
                        limit: categoryarticlesPerPage,
                        skip: i * categoryarticlesPerPage,
                        numPages,
                       currentPage: i + 1,
                    },
              })
          })
     })
    

    期望的结果是按类别计算文章的数量,这样类别分页就可以正常工作了(现在,它创建的页面比需要的页面要多,因为它考虑了网站上存在的全部文章数量)。

    有什么线索吗?

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Faizuddin Mohammed    6 年前
    const categoryarticles = categories.filter(category =>{
      return category === category
    })
    

    始终返回整个数组 category === category true . 其中之一 category 变量应该不同。你可能需要过滤一下 articles .

    而且,这似乎是一个完美的工作 _.flatMap ,就像这样:

    const categories = _.flatMap(result.data.allMarkdownRemark.edges, edge => {
      return _.get(edge, "node.frontmatter.categories", []);
    });
    
    // get articles from somewhere
    const categoryarticles = articles.filter(category => {
      return article.category === category;
    });
    

    如果要计算每个类别中的文章数,可以使用 _.countBy

    const categoryWiseArticleCount = _.countBy(articles, article => {
      // return the article category here
      return article.category;
    });
    
    console.log(categoryWiseArticleCount);
    // {
    //   category_1: 7,
    //   category_2: 10,
    // }