我见过的大多数盖茨比教程都只处理一个分页的来源。对于我的站点,我有多个页面使用GraphQL过滤不同类别的博客文章的160+。我需要一些方法来分页每个类别的网页,这样用户不必滚动数十篇文章,以达到网站页脚。但是像gatsby-awesome-pagination这样的在线解决方案只处理一个分页的来源。
是否有可能在多个页面之间进行分页?我想我必须自定义每个类别页面的GraphQL,以说明分页所需的每个页面的博客文章的差异?这个想法可能吗?
我的Github
发布于 2020-04-08 14:08:50
如果您命中了,您需要定制您的页面创建。在你的gatsby-node.js里
const posts = result.data.allMarkdownRemark.edges
const postsPerPage = 6
const numPages = Math.ceil(posts.length / postsPerPage)
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `/blog` : `/blog/${i + 1}`,
component: path.resolve("./src/templates/blog-list-template.js"),
context: {
limit: postsPerPage,
skip: i * postsPerPage,
numPages,
currentPage: i + 1,
},
})
})上面的代码将根据文章总数创建一定数量的页面。每一页都会列出postsPerPage(6)帖子,直到剩下的postsPerPage(6)帖子还不到为止。第一个页面的路径是/blog,下面的页面将具有表单的路径:/blog/2、/blog/3等。
请记住,您正在通过上下文将限制和当前页面传递给模板。因此,在您的博客模板中,查询应该如下所示:
query blogListQuery($skip: Int!, $limit: Int!) {
allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
limit: $limit
skip: $skip
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}您已经完成了,只需在组件中添加下一个和prev按钮/编号,如下所示:
Next/Prev按钮:
const { currentPage, numPages } = this.props.pageContext
const isFirst = currentPage === 1
const isLast = currentPage === numPages
const prevPage = currentPage - 1 === 1 ? "/" : (currentPage - 1).toString()
const nextPage = (currentPage + 1).toString()
return (
/* your code to display a list of posts */
{!isFirst && (
<Link to={prevPage} rel="prev">
← Previous Page
</Link>
)}
{!isLast && (
<Link to={nextPage} rel="next">
Next Page →
</Link>
)}
)编号:
const { currentPage, numPages } = this.props.pageContext
return (
// ...
{Array.from({ length: numPages }, (_, i) => (
<Link key={`pagination-number${i + 1}`} to={`/${i === 0 ? "" : i + 1}`}>
{i + 1}
</Link>
))}您可以查看更多详细信息,这里。
https://stackoverflow.com/questions/61101895
复制相似问题