【问题标题】:Gatsby Js Pagination : start root page at desired pageGatsby Js 分页:在所需页面开始根页面
【发布时间】:2021-04-16 18:00:45
【问题描述】:

我正在尝试使用 GatsbyJs 和 wordpress 作为无头 CMS 构建自己的博客。

我正在尝试对我的帖子页面进行分页,我找到了一种方法,但帖子从 blog/1 开始。如何格式化路径以便在 blog/ 设置第一页?

[我在开发和尝试自学方面完全是个菜鸟]

这是我的 gatsby-node.js

const path = require('path');

const allPostsQuery = `{
  allWpPost {
    edges {
      node {
        id
        slug
      }
    }
  }
}`;



const createPaginationPages = (component, totalItems, base, context, createPage) => {
  const pageSize = 4;
  const pageCount = Math.ceil(totalItems / pageSize);
  return Array.from({length: pageCount}).map((_, index) => createPage({
    path: `${base}/${ index+ 1}`,
    component,
    context: {
      base,
      limit: pageSize,
      skip: index * pageSize,
      pageCount,
      currentPage: index + 1,
      ...context
    },
  }));
};
 

// création de page pour chaque article
const createPostPages = ({allWpPost}, createPage) => {
  return allWpPost.edges.map(({node}) => createPage({
    path: `/blog/${node.slug}`,
    component: path.resolve('./src/templates/post.js'),
    context: {slug: node.slug}
  }));
};

//création de la page avec tous les articles 
const createPostsPages = ({allWpPost}, createPage) => createPaginationPages(
  path.resolve('./src/templates/blog.js'),
  allWpPost.edges.length,
  '/blog',
  {},
  createPage
);

exports.createPages = ({graphql, actions}) => {
  const {createPage} = actions;
  return graphql(allPostsQuery).then(({errors, data}) => {
    if (errors) return Promise.reject(errors);
    return [
      createPostPages(data, createPage),
      createPostsPages(data, createPage),
    ];
  });
};```




Thank you

【问题讨论】:

    标签: node.js reactjs graphql gatsby


    【解决方案1】:

    在这里改变你的逻辑:

    const createPaginationPages = (component, totalItems, base, context, createPage) => {
      const pageSize = 4;
      const pageCount = Math.ceil(totalItems / pageSize);
      return Array.from({length: pageCount}).map((_, index) => createPage({
        path: `${index === 0 ? `${base}/` : `${base}/${index + 1}`}`,
        component,
        context: {
          base,
          limit: pageSize,
          skip: index * pageSize,
          pageCount,
          currentPage: index + 1,
          ...context
        },
      }));
    };
    

    这里的三元条件可以解决问题:

    path: `${index === 0 ? `${base}/` : `${base}/${index + 1}`}`,
    

    如果您的index0,则路径将为base,否则,它将连接index + 1

    【讨论】:

      猜你喜欢
      • 2015-08-20
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 2014-06-12
      • 1970-01-01
      • 2016-07-10
      • 1970-01-01
      相关资源
      最近更新 更多