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

使用Next.js获取Sanity数据返回空数组的问题咨询

问题原因及解决方案

核心问题:GROQ查询的_type完全错误

你当前的GROQ查询用了document和array作为_type匹配值,但这两个都不是你创建的文章/分类对应的文档类型:

  • document是Sanity中所有文档的基类,不是你通过博客Schema创建的文章类型
  • array是字段类型(用来存储多值的字段类型),根本不属于文档类型范畴

Sanity官方博客模板默认的文档类型:

  • 文章:post
  • 分类:category

修改后的代码示例

import Image from "next/image";
import sanityClient from "@sanity/client";
import imageUrlBuilder from "@sanity/image-url";

export default function Home({ posts, categories }) {
  return (
    <div>
      sample
      {console.log(posts, categories)}
    </div>
  );
}

export const client = sanityClient({
  projectId: "c3sj114g",
  dataset: "production",
  apiVersion: "2022-10-02",
  useCdn: true,
  token: process.env.NEXT_PUBLIC_SANITY_TOKEN,
});

export const getServerSideProps = async () => {
  // 查询所有文章
  const postsQuery = `*[_type == "post"]`;
  const posts = await client.fetch(postsQuery);

  // 查询所有分类
  const categoriesQuery = `*[_type == "category"]`;
  const categories = await client.fetch(categoriesQuery);
  
  return {
    props: { posts, categories },
  };
};

额外排查点

  • 数据集一致性检查:确认Sanity Studio中你创建的文章/分类是存放在production数据集里,很多时候刚创建的内容会默认存入development数据集,需要对应修改代码里的dataset值
  • CDN缓存问题:如果刚在Sanity Studio更新了数据,开启useCdn: true可能会导致缓存未刷新,临时改成false测试是否能拿到数据
  • 权限验证:如果你的数据集是私有模式,确保NEXT_PUBLIC_SANITY_TOKEN拥有读取该数据集的权限(公开数据集不需要token也能读取)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:31:20