【发布时间】:2020-07-24 16:45:41
【问题描述】:
看了分页教程,不明白分页是怎么渲染的?正在使用哪个页面? blog-list-template 是被传递到页面文件夹中的文件的组件吗?如果没有,那么在没有指定文件的情况下,gatsby 怎么知道使用blog-list-template?
【问题讨论】:
-
这能回答你的问题吗? Gatsby Pagination for multiple pages
看了分页教程,不明白分页是怎么渲染的?正在使用哪个页面? blog-list-template 是被传递到页面文件夹中的文件的组件吗?如果没有,那么在没有指定文件的情况下,gatsby 怎么知道使用blog-list-template?
【问题讨论】:
在教程示例中,查看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,
})
}
}
首先它会查询allMarkdownRemark。
然后它将根据上述查询使用createPage 找到的帖子总数创建一定数量的页面。
它使用blog-list-template 和页面的context 中有关分页的一些信息来创建每个页面。 (请注意,因此$skip 和$limit 可用作blog-list-template 的graphql 查询中的变量。)
每个页面将列出 6 个帖子,直到剩下的帖子少于 6 个 (const postsPerPage = 6)。
/blog,后续页面路径为:/blog/2、/blog/3等。【讨论】: