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



在我的Gatsby JS网站中,我对文章进行了分类,我设法为每个类别创建了一个页面,并根据页面上显示的最大文章数量对每个页面进行分页。问题是,我的代码不是计算每个类别的现有页面的确切数量,而是计算现有页面的总数(基于所有文章,而不是按类别计算的文章)。

这是代码:

盖茨比节点.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,
                },
          })
      })
 })

错误无疑出在常量类别文章中。

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

有什么线索吗?

谢谢。

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

最新更新