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

如何用GraphQL与动态嵌套路径创建Next.js getStaticPaths函数?

修复后的getStaticPaths实现

你的代码存在两个核心问题:一是两次调用map时直接覆盖了paths变量,导致分类(categories)的路径全部丢失,最终只保留了文章(posts)的路径;二是未处理数据为空的边界情况,若pages或posts节点不存在,map会抛出错误。

以下是修正后的代码:

export async function getStaticPaths() {
  const GET_ALL_SLUGS = gql`
    query getAllSlugs {
      posts {
        nodes {
          slug
        }
      }
      pages {
        nodes {
          slug
        }
      }
    }
  `;
  const response = await client.query({
    query: GET_ALL_SLUGS,
  });

  // 用空数组兜底,避免map报错
  const categories = response?.data?.pages?.nodes || [];
  const posts = response?.data?.posts?.nodes || [];

  // 分别生成分类和文章的路径数组
  const categoryPaths = categories.map(({ slug }) => ({
    params: { category: slug },
  }));
  
  const postPaths = posts.map(({ slug }) => ({
    params: { post: slug },
  }));

  // 合并所有路径
  const paths = [...categoryPaths, ...postPaths];

  return {
    paths,
    fallback: false,
  };
}

关键修正点:

  • 用|| []为categories和posts设置空数组兜底,确保即使接口返回空数据也不会触发map方法的错误。
  • 分别生成分类路径数组和文章路径数组,再通过扩展运算符...合并成最终的paths数组,避免覆盖问题。
  • 移除了多余的初始paths赋值,简化逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 23:31:12