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

getStaticPaths中tags参数返回null问题求助

解决getStaticPaths传递tags参数为null的问题

问题分析

你在getStaticPaths中尝试返回slug和tags参数,但getStaticProps中仅能正常获取slug,tags始终为null。手动替换tags为具体值可查询成功,说明核心问题出在getStaticPaths阶段的参数传递环节——要么是Sanity查询未正确获取到tags值,要么是生成的params包含无效的tags数据。

解决方案步骤

1. 先验证Sanity查询返回的tags有效性

在getStaticPaths中添加日志,确认从Sanity获取的chapters数据里tags是否存在且为字符串:

export async function getStaticPaths() {
  const chapters = await client.fetch(
    `*[_type == "chapters" && defined(slug.current)] {
      "slug": slug.current,
      "tags": tags
    }`
  );
  // 打印日志验证数据
  console.log('获取到的章节数据:', chapters);
  return {
    paths: chapters.map((s : any) => ({params: {slug : s.slug,tags: s.tags}})),
    fallback: false,
  }
}

如果日志中显示部分或全部tags为null,说明Sanity文档中该字段为空,或者查询语句有问题。

2. 过滤无效数据,确保tags为有效字符串

修改Sanity查询和后续处理逻辑,只保留tags存在且为字符串的文档:

export async function getStaticPaths() {
  // 查询时直接过滤掉tags为空的文档
  const chapters = await client.fetch(
    `*[_type == "chapters" && defined(slug.current) && defined(tags) && typeof(tags) == "string"] {
      "slug": slug.current,
      "tags": tags
    }`
  );
  // 二次过滤避免意外情况
  const validChapters = chapters.filter(chapter => chapter.tags.trim() !== '');
  return {
    paths: validChapters.map((s : any) => ({params: {slug : s.slug,tags: s.tags}})),
    fallback: false,
  }
}

3. 在getStaticProps中显式处理参数类型

即使传递了有效参数,也可能存在类型转换问题,可显式确保tags为字符串:

export async function getStaticProps(context: any) {
  const { slug = "", tags = "" } = context.params;
  // 强制转换为字符串,避免非预期类型
  const validTag = typeof tags === 'string' ? tags.trim() : '';
  const suggestions = await client.fetch(`
  *[_type == "chapters" && tags == $tags][0]
`, { tags: validTag });
  // 后续业务逻辑...
}

4. 检查Sanity Schema定义

确认你的Sanity章节文档中,tags字段确实定义为字符串类型,而非数组或其他类型:

// sanity/schemas/chapters.js
export default {
  name: 'chapters',
  type: 'document',
  fields: [
    // 其他字段
    {
      name: 'tags',
      type: 'string',
      title: '标签'
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:35:26