You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gatsby+Strapi分页实现失败求助:附代码及报错问题

Gatsby + Strapi 新闻列表分页问题排查与解决

常见报错场景与修复方案

1. gatsby-node.js 分页逻辑错误

问题表现

运行 gatsby develop 时抛出 GraphQL 查询错误、页面生成失败,或分页参数传递异常。

修复步骤

  • 确保正确计算总页数并传递分页上下文参数:
    exports.createPages = async ({ graphql, actions }) => {
      const { createPage } = actions;
      const result = await graphql(`
        query {
          allStrapiNews {
            totalCount
            nodes {
              id
            }
          }
        }
      `);
    
      const postsPerPage = 6;
      const numPages = Math.ceil(result.data.allStrapiNews.totalCount / postsPerPage);
    
      Array.from({ length: numPages }).forEach((_, i) => {
        createPage({
          path: i === 0 ? `/njoftime` : `/njoftime/${i + 1}`,
          component: require.resolve("./src/pages/njoftime.js"),
          context: {
            limit: postsPerPage,
            skip: i * postsPerPage,
            numPages,
            currentPage: i + 1,
          },
        });
      });
    };
    
  • 检查 context 中的 limit、skip、currentPage、numPages 参数是否完整,这些是页面组件查询数据的核心依据。

2. njoftime.js GraphQL 查询错误

问题表现

页面加载时显示查询失败,或无法获取对应分页的新闻数据。

修复步骤

  • 利用 pageContext 参数构建分页查询:
    import React from "react";
    import { graphql } from "gatsby";
    
    const NewsList = ({ data, pageContext }) => {
      const { currentPage, numPages } = pageContext;
      const news = data.allStrapiNews.nodes;
    
      return (
        <div>
          <h1>新闻列表</h1>
          <ul>
            {news.map(item => (
              <li key={item.id}>{item.title}</li>
            ))}
          </ul>
          <div className="pagination">
            {currentPage > 1 && (
              <a href={`/njoftime/${currentPage - 1}`}>上一页</a>
            )}
            {Array.from({ length: numPages }).map((_, i) => (
              <a
                key={i + 1}
                href={`/njoftime/${i + 1 === 1 ? "" : i + 1}`}
                className={currentPage === i + 1 ? "active" : ""}
              >
                {i + 1}
              </a>
            ))}
            {currentPage < numPages && (
              <a href={`/njoftime/${currentPage + 1}`}>下一页</a>
            )}
          </div>
        </div>
      );
    };
    
    export const query = graphql`
      query($skip: Int!, $limit: Int!) {
        allStrapiNews(limit: $limit, skip: $skip, sort: {publishedAt: DESC}) {
          nodes {
            id
            title
            publishedAt
            excerpt
          }
        }
      }
    `;
    
    export default NewsList;
    
  • 必须添加 sort 参数避免数据顺序混乱,同时验证 skip 和 limit 变量是否正确接收。

3. Strapi 数据权限或配置问题

问题表现

Gatsby 无法获取 Strapi 新闻数据,查询返回空数组。

修复步骤

  • 检查 Strapi 中 News 内容类型的公开权限是否开启,确保未登录状态下能读取数据;
  • 确认查询中请求的字段(如 title、publishedAt)在 Strapi 中已配置为可查询;
  • Strapi v4 需在 gatsby-config.js 中指定查询上限:
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-strapi`,
          options: {
            apiURL: process.env.STRAPI_API_URL || `http://localhost:1337`,
            accessToken: process.env.STRAPI_TOKEN,
            collectionTypes: [`news`],
            singleTypes: [],
            queryLimit: 1000,
          },
        },
      ],
    };
    

4. 分页路径冲突

问题表现

访问分页页面(如 /njoftime/2)时显示 404,或内容与第一页重复。

修复步骤

  • 确保 gatsby-node.js 生成的路径与路由规则一致,避免和 src/pages 下的文件重名;
  • 清理 Gatsby 缓存后重新构建:运行 gatsby clean && gatsby develop。

内容的提问来源于stack exchange,提问作者Petro Tafilaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 07:52:40