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

如何为gatsbyjs中属于特定类别的帖子列表分页

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

    我已经开发了一个与盖茨比js博客,我设法添加到每个降价文件的类别,以便我可以通过查询一个特定的类别创建页面,并列出所有与该类别相关的帖子。 现在,我试图添加分页,以避免在每个类别页面中出现无限的帖子列表。

    我一直遵循官方指南: https://www.gatsbyjs.org/docs/adding-pagination/

    这就是我想出的密码:

    盖茨比节点.js

    const path = require('path')
    const _ = require("lodash")
    const { createFilePath } = require("gatsby-source-filesystem")
    
    exports.createPages = ({actions, graphql}) => {
    const {createPage} = actions
    
    const articleTemplate = path.resolve(`src/templates/article.js`)
    const categoryTemplate = path.resolve("src/templates/category.js")
    
    return new Promise((resolve, reject) => {
        resolve(
          graphql(
              `
                {
                    allMarkdownRemark(
                        sort: { order: DESC, fields: [frontmatter___date] }
                        limit: 2000
                    ) {
                        edges {
                            node {
                                html
                                id
                                frontmatter {
                                    path
                                    title
                                    categories
                                }
                            }
                        }
                    }
                }
    
        `).then(result => {
            if (result.errors) {
                reject(result.errors)
            }
    
            const articles = result.data.allMarkdownRemark.edges
            const articlesPerPage = 6
            const numPages = Math.ceil(articles.length / articlesPerPage)
    
            //Creating a page for each article
            articles.forEach(({ node }) => {
                createPage({
                path: node.frontmatter.path,
                component: articleTemplate,
                //context: {}, // additional data can be passed via context
                })
            })
    
            // Categories pages:
            let categories = []
            // Iterate through each article, putting all found categories into `categories`
            _.each(articles, edge => {
                if (_.get(edge, "node.frontmatter.categories")) {
                    categories = categories.concat(edge.node.frontmatter.categories)
                }
            })
    
    
            Array.from({ length: numPages }).forEach((category, _, i) => {
                createPage({
                  path: i === 0 ? `/${_.kebabCase(category)}/` : `/${_.kebabCase(category)}/${i + 1}`,
                  component: categoryTemplate,
                  context: {
                    limit: articlesPerPage,
                    skip: i * articlesPerPage,
                    category,
                  },
                })
            })
        })
    )
    })
    

    /模板/类别.js

    import React from "react"
    import PropTypes from "prop-types"
    import Layout from '../layouts/layout'
    import ArticleCard from '../components/articles/articlecard'
    
    // Components
    import { Link, graphql } from "gatsby"
    
    const _ = require("lodash")
    
    const Categories = ({ pageContext, data }) => {
      const { category } = pageContext
      const { edges } = data.allMarkdownRemark
    
      return (
        <Layout>
            <section class="hero is-info is-medium has-text-centered">
                <div class="hero-body">
                    <div class="container">
                        <h1 class="title is-top">
                            {category}
                        </h1>
                    </div>
                </div>
            </section>
            <div class="section">
                <div class="container">
                    <div class="columns is-multiline">
                        {edges.map(({ node }) => {
                            const { path, title, date } = node.frontmatter
                            return (
                                <div class="column is-half">
                                    <div class="card">
                                        <div class="card-header">
                                            <p class="card-header-content">{date}</p>
                                        </div>
                                        <div class="card-content">
                                        <Link to={_.kebabCase(category)}><span class="tag is-success has-padding">{category}</span></Link>
                                            <Link to={path}>
                                                <h2 class="title is-4">{title}</h2>
                                            </Link>
                                        </div>
                                        <div class="card-footer">
                                            <div class="card-footer-item"><Link to={path}><div class="button is-success is-inverted is-fullwidth">Read</div></Link></div>
                                            <div class="card-footer-item"><Link to={path}><div class="button is-info is-inverted is-fullwidth">Share on Linkedin</div></Link></div>
                                        </div>        
                                    </div>
                                </div>
                            )
                        })}
                    </div>
                </div>
            </div>
        </Layout>
      )
    }
    
    Categories.propTypes = {
      pageContext: PropTypes.shape({
        category: PropTypes.string.isRequired,
      }),
      data: PropTypes.shape({
       allMarkdownRemark: PropTypes.shape({
          totalCount: PropTypes.number.isRequired,
          edges: PropTypes.arrayOf(
            PropTypes.shape({
              node: PropTypes.shape({
                frontmatter: PropTypes.shape({
                  path: PropTypes.string.isRequired,
                  title: PropTypes.string.isRequired,
                }),
              }),
            }).isRequired
          ),
        }),
      }),
    }
    
    export default Categories
    
    export const pageQuery = graphql`
      query($skip: Int!, $limit: Int!, $category: String) {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          filter: { frontmatter: { categories: { in: [$category] } } }
          limit: $limit
          skip: $skip
        ) {
          totalCount
          edges {
            node {
              frontmatter {
                title
                path
                date(formatString: "MMMM DD, YYYY")
              }
            }
          }
        }
      }
    `
    

    这不起作用,现在正在抛出错误:error gatsby-node.js返回错误,typeerror:。kebabcase不是函数

    不过,在修改查询以添加分页之前,kebabcase使用得很顺利,所以我认为问题实际上并不存在。

    有人知道吗?

    谢谢您!

    0 回复  |  直到 6 年前
        1
  •  1
  •   Yassine Bridi    5 年前

    您要声明变量“下划线”两次:
    1-来自洛达斯图书馆
    2-来自foreach函数:

    Array.from({ length: numPages }).forEach((category, _, i)
    

    只需将第二个变量更改为另一个任意名称,如下所示:

    Array.from({ length: numPages }).forEach((category, otherName, i)