Sanity嵌套数组/引用无法正常工作的问题求助
问题解决:Sanity页面无法读取offerContent.content字段
核心原因
你尝试直接渲染block.offerContent.content,但它是Portable Text块数组,不能像普通字符串那样直接插入JSX,必须用@portabletext/react组件解析渲染。另外代码里还有Image组件的参数错误,也会导致异常。
修复步骤
1. 修正Offer内容的渲染方式
把渲染代码中<h2>{block.offerContent.content}</h2>替换为PortableText组件:
// 原错误代码 <h2>{block.offerContent.content}</h2> // 替换为 <PortableText value={block.offerContent.content} />
2. 修复Image组件的参数错误
原代码引用了不存在的product.image和product.alt,需要对应Sanity返回的图片结构修正:
// 原错误代码 {product.image ? ( <Image src={product.headerImage} alt={product.alt} width={1000} height={1000} /> ) : null} // 替换为 {product.headerImage?.asset?.url ? ( <Image src={product.headerImage.asset.url} alt={product.headerImage.alt || product.title} width={1000} height={1000} /> ) : null}
这里用可选链?.避免空值报错,同时给alt设置兜底值。
3. 补充其他Content类型的查询(可选)
当前GROQ查询只处理了offer类型,若后续需要渲染advantages或faq,可以补充对应字段:
content[]{ _type == "offer" => {_type, title, text, offerContent{content}}, _type == "advantages" => {_type, /* 补充advantages的字段 */}, _type == "faq" => {_type, /* 补充faq的字段 */} }
完整修正后的渲染代码
import { getProduct } from "@/sanity/sanity-utils"; import { PortableText } from "@portabletext/react"; import Image from "next/image"; type Props = { params: { product: string }; }; export default async function Product({ params }: Props) { const slug = params.product; const product = await getProduct(slug); return ( <div> <h1>{product.title}</h1> <PortableText value={product.headerText} /> {product.headerImage?.asset?.url ? ( <Image src={product.headerImage.asset.url} alt={product.headerImage.alt || product.title} width={1000} height={1000} /> ) : null} <div> {product.content.map((block: any, index: any) => { switch (block._type) { case "offer": return ( <div key={index}> <p>{block.title}</p> <p>{block.text}</p> <PortableText value={block.offerContent.content} /> </div> ); // 可在此补充advantages和faq的渲染逻辑 // case "advantages": // return <div key={index}>...</div>; default: return null; } })} </div> </div> ); }
内容的提问来源于stack exchange,提问作者Amanda Hultén
相关产品推荐
相关产品推荐

