【问题标题】:Gatsby Website Prev and Next link under each single post每个帖子下的 Gatsby 网站上一个和下一个链接
【发布时间】:2020-01-15 01:13:58
【问题描述】:

我想在每个帖子下显示 Prev 和 Next 链接。我按照下面的教程并合并到我的项目中,我的网站结构与教程中的不同。

https://egghead.io/lessons/gatsby-add-next-and-previous-links-to-a-gatsby-blog

这是我的 gatsby-node.js 文件:https://prnt.sc/qmdmhi 和我的 post.js 文件:https://prnt.sc/qmdmdh

合并此代码后,帖子未创建且无法查看链接。

POST.JS

/* eslint-disable react/no-danger */
import React from "react";
import { graphql } from 'gatsby';
import PropTypes from 'prop-types';
import styled from 'styled-components';

import Layout from '../components/layout';
import Breadcrumb from '../components/BreadCrumb';
import PostSidebar from '../components/post/PostSidebar';
import PageHero from '../components/PageHero';
import PageTransition from 'gatsby-plugin-page-transitions';

import ShareButtons from "../components/ShareButtons";

const PostContent = styled.article`
  margin: 20px 0 0 0;
`;

const postTemplate = ({ data: { post }, pageContext }) => {
  const {next,prev} = pageContext
  return(  

<PageTransition>
<Layout>
    <PageHero img={post.featured_media.localFile.childImageSharp.fluid} />


    <Breadcrumb
      parent={{
        link: '/blogs/all-blogs',
        title: 'blogs',
      }}
    />
    <div className="container">
      <div className="row" style={{ marginBottom: '40px' }}>
        <PostSidebar
          date={post.date}
          author={post.author.name}
          categories={post.categories}
        />
        <PostContent className="col-lg-9">
          <h1 dangerouslySetInnerHTML={{ __html: post.title }} />
          <div dangerouslySetInnerHTML={{ __html: post.content }} />
        <ShareButtons/>
        {next && <Link to={next.post.slug}>Next</Link>}
        {prev && <Link to={prev.post.slug}>Prev</Link>}
        </PostContent>
      </div>
    </div>

    </Layout>
  </PageTransition>
); 
};

postTemplate.propTypes = {
  data: PropTypes.object.isRequired,
};

export default postTemplate;

export const pageQuery = graphql`
  query($id: String!) {
    post: wordpressPost(id: { eq: $id }) {
      id 
      title
      content
      excerpt
      slug
      author {
        name
      }
      date(formatString: "DD, MMM, YYYY")
      categories {
        id
        name
        slug
      }

      featured_media {
        source_url
        localFile {
          relativePath 
          childImageSharp {
            fluid(quality: 100, maxWidth: 900) {
              ...GatsbyImageSharpFluid_withWebp
            src
            }
          }
        }
      }
    }
    }
  `;

Gatsby-node.js

const path = require('path');
const slash = require('slash');
const { paginate } = require('gatsby-awesome-pagination');

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

  const pageTemplate = path.resolve('./src/templates/page.js');
  const archiveTemplate = path.resolve('./src/templates/archive.js');
  const postTemplate = path.resolve('./src/templates/post.js');

  const result = await graphql(`
    {
      allWordpressPage {
        edges {
          node {
            id
            status
            link
            wordpress_id
            wordpress_parent
          }
        }
      }
      allWordpressPost(filter: {status: {eq: "publish"}}) {
        edges {
          node {
            id
            link
            status
            categories {
              id
            }
            featured_media {
              localFile{
                  childImageSharp {
                      id
                  } 
              }
          }   
          }
        }
      }
      allWordpressCategory {
        edges {
          node {
            id
            name
            slug
            count
          }
        }
      }

      allSite {
        edges {
          node {
            siteMetadata {
              title
              description
              author
            }
          }
        }
      }
     }
  `);

  // Check for errors
  if (result.errors) {
    throw new Error(result.errors);
  }

  const {
    allWordpressPage,
    allWordpressPost,
    allWordpressCategory,
  } = result.data;

  exports.onCreateWebpackConfig = ({ actions }) => {
    actions.setWebpackConfig({
        devtool: "eval-source-map"
    });
};

  // Create archive pages for each category
  allWordpressCategory.edges.forEach(catEdge => {
    // First filter out the posts that belongs to the current category
    const filteredPosts = allWordpressPost.edges.filter(
      ({ node: { categories } }) =>
        categories.some(el => el.id === catEdge.node.id)
    );
    // Some categories may be empty and we don't want to show them
    if (filteredPosts.length > 0) {
      paginate({
        createPage,
        items: filteredPosts,
        itemsPerPage: 10,
        pathPrefix: 
        catEdge.node.slug === "blogs"
        ? "/blogs"
        : `/blogs/${catEdge.node.slug}`,
        component: slash(archiveTemplate),
        context: {
          catId: catEdge.node.id,
          catName: catEdge.node.name,
          catSlug: catEdge.node.slug,
          catCount: catEdge.node.count,
          categories: allWordpressCategory.edges,
        },
      });
    }
  });

  allWordpressPage.edges.forEach(edge => {
    if (edge.node.status === 'publish') {
      createPage({
        path: edge.node.link,
        component: slash(pageTemplate),
        context: {
          id: edge.node.id,
          parent: edge.node.wordpress_parent,
          wpId: edge.node.wordpress_id,
        },
      });
    }
  });

  const posts =result.data.allWordpressPost.edges
  posts.forEach(({edge},index)=>{
  /*allWordpressPost.edges.forEach(edge => {*/

      createPage({
        path: `/blogs${edge.node.link}`,
        component: slash(postTemplate),
        context: {
          id: edge.node.id,
        },
      });

  });

};

【问题讨论】:

  • 请在问题中包含相关代码。
  • 我粘贴了我的代码。请立即检查。

标签: javascript node.js reactjs wordpress gatsby


【解决方案1】:
  1. 您尚未在 gatsby-node.js 文件中传递 context 上的 nextprev 属性。
  2. 这将失败,因为结构是 edges = [{ node: {...} }](没有要解构的 edge 属性):posts.forEach(({edge},index)=&gt;{

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2016-12-10
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多