尝试重定向分页链接中的帖子时gatsby-node.js中发生错误

问题描述

尝试在gatsby博客中部署分页时出现以下错误

图片一:gatsby-node.js" threw an error while running the createPages lifecycle

图片二: failed createPages - 0.458s

这就像是逻辑失败,但我不明白为什么。我将留下一个现场演示,以便您可以看到确切的错误。加载页面后,我可以访问帖子,但是,如果我转到页面2,那么,如果我尝试访问该帖子,则会收到404,因为它没有重定向到正确的链接。 / p>

Web Demo

gatsby-node.js文件

const path = require('path');
const { slugify } = require('./src/util/utilityFunctions');
const authors = require('./src/util/authors');
const _ = require('lodash');

exports.onCreateNode = ({ node,actions }) => {
    const { createNodeField } = actions;
    if (node.internal.type === 'MarkdownRemark') {
        const slugFromTitle = slugify(node.frontmatter.title);
        createNodeField({
            node,name: 'slug',value: slugFromTitle
        });
    }
};

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

    // Page templates
    const templates = {
        post: path.resolve('src/templates/single-post.js'),postList: path.resolve('src/templates/post-list.js'),tag: path.resolve('src/templates/tag-posts.js'),tagsPage: path.resolve('src/templates/tags-page.js'),authorPosts: path.resolve('src/templates/author-posts.js')
    };

    const res = await graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            frontmatter {
              author
              tags
            }
            fields {
              slug
            }
          }
        }
      }
    }
  `);

    if (res.errors) return Promise.reject(res.errors);

    // Extracting all posts from res
    const posts = res.data.allMarkdownRemark.edges;

    // Create single post pages
    posts.forEach(({ node }) => {
        createPage({
            path: node.fields.slug,component: templates.post,context: {
                // Passing slug for template to use to fetch the post
                slug: node.fields.slug,// Find author imageUrl from author array and pass it to template
                imageUrl: authors.find((x) => x.name === node.frontmatter.author).imageUrl
            }
        });
    });

    // Create posts pagination pages
    const postsPerPage = 3;
    const numberOfPages = Math.ceil(posts.length / postsPerPage);

    Array.from({ length: numberOfPages }).forEach((_,index) => {
        const isFirstPage = index === 0;
        const currentPage = index + 1;

        // Skip first page because of index.js
        if (isFirstPage) return;

        createPage({
            path: `/page/${currentPage}`,component: templates.postList,context: {
                limit: postsPerPage,skip: index * postsPerPage,numberOfPages: numberOfPages,currentPage: currentPage
            }
        });
    });
    // Get all tags
    let tags = [];
    _.each(posts,(edge) => {
        if (_.get(edge,'node.frontmatter.tags')) {
            tags = tags.concat(edge.node.frontmatter.tags);
        }
    });

    let tagPostCounts = {}; // { tutorial: 2,design: 1}
    tags.forEach((tag) => {
        // Or 0 cause it might not exist yet
        tagPostCounts[tag] = (tagPostCounts[tag] || 0) + 1;
    });

    // Remove duplicates
    tags = _.uniq(tags);

    // Tags page (all tags)
    createPage({
        path: '/tags',component: templates.tagsPage,context: {
            tags,tagPostCounts
        }
    });

    // Tag posts pages
    tags.forEach((tag) => {
        createPage({
            path: `/tag/${_.kebabCase(tag)}`,component: templates.tag,context: {
                tag
            }
        });
    });

    // Create author posts pages
    authors.forEach((author) => {
        createPage({
            path: `/author/${slugify(author.name)}`,component: templates.authorPosts,context: {
                authorName: author.name,imageUrl: author.imageUrl
            }
        });
    });
};

PaginationLinks.js页面查看分页逻辑

import React from 'react'
import { Pagination,PaginationItem,PaginationLink } from 'reactstrap'

const PaginationLinks = ({ currentPage,numberOfPages }) => {
  const isFirst = currentPage === 1
  const isLast = currentPage === numberOfPages
  const prevIoUsPage =
    currentPage - 1 === 1 ? '/' : '/page/' + (currentPage - 1).toString()
  const nextPage = '/page/' + (currentPage + 1).toString()
  return (
    <Pagination aria-label="Page navigation example">
      {isFirst ? (
        <PaginationItem disabled>
          <PaginationLink prevIoUs href="/" />
        </PaginationItem>
      ) : (
        <PaginationItem>
          <PaginationLink prevIoUs href={prevIoUsPage} />
        </PaginationItem>
      )}
      {Array.from({ length: numberOfPages },(_,i) =>
        currentPage === i + 1 ? (
          <PaginationItem active key={`page-number${i + 1}`}>
            <PaginationLink href={`/${i === 0 ? '' : 'page/' + (i + 1)}`}>
              {i + 1}
            </PaginationLink>
          </PaginationItem>
        ) : (
          <PaginationItem key={`page-number${i + 1}`}>
            <PaginationLink href={`/${i === 0 ? '' : 'page/' + (i + 1)}`}>
              {i + 1}
            </PaginationLink>
          </PaginationItem>
        )
      )}
      {isLast ? (
        <PaginationItem disabled>
          <PaginationLink next href={nextPage} />
        </PaginationItem>
      ) : (
        <PaginationItem>
          <PaginationLink next href={nextPage} />
        </PaginationItem>
      )}
    </Pagination>
  )
}

export default PaginationLinks

post-list.js页面查看查询

import React from 'react';
import Layout from '../components/layout';
import Post from '../components/Post';
import { graphql } from 'gatsby';
import PaginationLinks from '../components/PaginationLinks';

const postList = (props) => {
    const posts = props.data.allMarkdownRemark.edges;
    const { currentPage,numberOfPages } = props.pageContext;

    return (
        <Layout pageTitle={`Page: ${currentPage}`}>
            {posts.map(({ node }) => (
                <Post
                    key={node.id}
                    slug={node.fields.slug}
                    title={node.frontmatter.title}
                    author={node.frontmatter.author}
                    date={node.frontmatter.date}
                    body={node.excerpt}
                    tags={node.frontmatter.tags}
                    fluid={node.frontmatter.image.childImageSharp.fluid}
                />
            ))}
            <PaginationLinks currentPage={currentPage} numberOfPages={numberOfPages} />
        </Layout>
    );
};

export const postListQuery = graphql`
    query postListQuery($skip: Int!,$limit: Int!) {
        allMarkdownRemark(sort: { fields: [frontmatter___date],order: DESC },limit: $limit,skip: $skip) {
            edges {
                node {
                    id
                    frontmatter {
                        title
                        date
                        author
                        tags
                        image {
                            childImageSharp {
                                fluid(maxWidth: 650,maxHeight: 371) {
                                    ...GatsbyImageSharpFluid
                                }
                            }
                        }
                    }
                    fields {
                        slug
                    }
                    excerpt
                }
            }
        }
    }
`;

export default postList;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...