Next.js从Sanity获取数据返回undefined问题排查
问题原因
控制台输出undefined是全链路命名、字段配置不匹配导致的,一共3处核心错误:
- Schema文档类型名和GROQ查询条件不匹配:你schema里
name字段写的是testimonials(复数),但查询语句里写的是*[_type == "testimonial"](单数),Sanity的_type值直接取schema中配置的name字段,二者不一致时根本查不到任何匹配数据。 - Props命名不匹配:
getServerSideProps返回给组件的字段叫testimonials(复数),但组件内解构、类型定义写的都是testimonial(单数),字段名对不上自然拿不到值。另外你原来写的[Testimonial]是固定长度为1的元组类型,和实际返回的任意长度文档数组类型也不匹配。 - 字段定义不匹配:GROQ查询、TS类型里声明的
slug、description、author三个字段,在原始schema里完全没有定义,就算查到数据这几个字段也会返回null;同时schema里的preview配置也写错了,选中的title字段指向了不存在的testimonials属性。
修正方案
1. 修正Sanity Schema配置(testimonials.js)
统一_type命名,补全缺失字段,修正preview配置:
export default { name: "testimonial", // 这里统一用单数,和后续GROQ查询保持一致;如果想用复数,全链路统一命名即可 title: "Testimonials", type: "document", fields: [ { name: "title", title: "Title", type: "string", }, { name: "slug", title: "Slug", type: "slug", options: { source: "title", maxLength: 96, }, }, { name: "author", title: "Author", type: "string", }, { name: "description", title: "Description", type: "text", }, { name: "publishedAt", title: "Published at", type: "datetime", }, { name: "body", title: "Text", type: "blockContent", }, ], preview: { select: { title: "title", // 指向实际存在的title字段 }, }, };
改完本地schema记得去Sanity后台重新部署schema,否则新字段不会生效,已经创建的旧文档也要补全新增字段的内容。
2. 修正组件Props接收逻辑(Testimonials.tsx)
对齐返回的props字段名,修正类型定义:
interface Props { testimonials: Testimonial[] // 和getServerSideProps返回的字段名保持一致,用数组类型替代原来的元组类型 } const Testimonials = ({ testimonials } : Props) => { console.log(testimonials) // 改完这里就能正常打印查询到的数据 return ( <div className="testimonials_info"> <h5>TESTIMONIALS</h5> {/* 后续遍历testimonials数组渲染内容即可 */} </div> ) } export default Testimonials
3. 对齐TS类型定义(typing.d.tsx)
补全缺失字段的类型声明:
export interface Testimonial { _id: string; _createdAt: string; title: string; description: string; author: string; publishedAt: string; slug: { current: string; }; body: any[]; // blockContent是富文本块数组,可根据自身业务替换为更精准的富文本类型 }
如果你不想把schema的
name改成testimonial,直接把GROQ查询里的_type == "testimonial"改成_type == "testimonials"即可,单复数本身没有对错,全链路命名统一就不会出问题。
内容的提问来源于stack exchange,提问作者Julia Schafer
相关产品推荐
相关产品推荐

