【问题标题】:How is Gatsby Blog List pagination rendered?Gatsby 博客列表分页是如何呈现的?
【发布时间】:2020-07-24 16:45:41
【问题描述】:

看了分页教程,不明白分页是怎么渲染的?正在使用哪个页面? blog-list-template 是被传递到页面文件夹中的文件的组件吗?如果没有,那么在没有指定文件的情况下,gatsby 怎么知道使用blog-list-template

Tutorial

【问题讨论】:

标签: graphql gatsby


【解决方案1】:

在教程示例中,查看gatsby-node.js 的代码。

const path = require("path")
const { createFilePath } = require("gatsby-source-filesystem")

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions

  // 1.
  const result = await graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `
  )

  if (result.errors) {
    reporter.panicOnBuild(`Error while running GraphQL query.`)
    return
  }

  // ...

  // Create blog-list pages
  const posts = result.data.allMarkdownRemark.edges
  const postsPerPage = 6
  const numPages = Math.ceil(posts.length / postsPerPage)

  // 2.
  Array.from({ length: numPages }).forEach((_, i) => {
    createPage({
      // 4. 
      path: i === 0 ? `/blog` : `/blog/${i + 1}`,

      // 3.
      component: path.resolve("./src/templates/blog-list-template.js"),
      context: {
        limit: postsPerPage,
        skip: i * postsPerPage,
        numPages,
        currentPage: i + 1,
      },
    })
  })
}

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  if (node.internal.type === `MarkdownRemark`) {
    const value = createFilePath({ node, getNode })
    createNodeField({
      name: `slug`,
      node,
      value,
    })
  }
}
  1. 首先它会查询allMarkdownRemark

  2. 然后它将根据上述查询使用createPage 找到的帖子总数创建一定数量的页面。

  3. 它使用blog-list-template 和页面的context 中有关分页的一些信息来创建每个页面。 (请注意,因此$skip$limit 可用作blog-list-template 的graphql 查询中的变量。)

每个页面将列出 6 个帖子,直到剩下的帖子少于 6 个 (const postsPerPage = 6)。

  1. 首页路径为/blog,后续页面路径为:/blog/2/blog/3等。

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 2020-07-24
    • 2021-02-15
    • 2021-02-06
    • 1970-01-01
    • 2014-09-11
    • 2016-12-14
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多