Gatsby入门指南—添加上一页下一页功能(5)

1.调整gatsby-node

这个就简单了,打开gatsby-node.js,增加代码如下:

    const path = require("path");
    exports.createPages = ({ actions, graphql }) => {
      const { createPage } = actions
      const blogPostTemplate = path.resolve(`src/templates/blogPost.js`)
      return graphql(`
        {
          allMarkdownRemark {
            edges {
              node {
                frontmatter {
                  path,
                  title,
                  tags
                }
              }
            }
          }
        }
      `).then(result => {
        if (result.errors) {
          return Promise.reject(result.errors)
        }
        const posts = result.data.allMarkdownRemark.edges;
        createTagPages(createPage, posts);
        posts.forEach(({ node }, index) => {
          const path = node.frontmatter.path;
          const title = node.frontmatter.title;
          createPage({
            title,
            path,
            component: blogPostTemplate,
            context: {
              pathSlug: path,
              //这里是新增加的
              prev: index === 0 ? null : posts[index - 1].node,
              next: index === (posts.length - 1) ? null : posts[index + 1].node
            }, // additional data can be passed via context
          })
        })
      })
    }

2.调整blogPost.js

    import React from "react"
    import { graphql,Link } from 'gatsby'
    const Template = ({ data, pageContext }) => {
      const {next,prev} = pageContext;
      const {markdownRemark} = data;
      const title = markdownRemark.frontmatter.title;
      const html = markdownRemark.html;
      return (
    
        

{title}

{next&&Next} {prev&&Prev}
) } export const query = graphql` query($pathSlug: String!) { markdownRemark(frontmatter: { path: { eq: $pathSlug } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") path title } } } ` export default Template;

打开首页,点击页面跳转到对应的页面大功告成。

你可能感兴趣的:(Gatsby入门指南—添加上一页下一页功能(5))