Next.js搭配Sanity开发时如何检查数据对象中的属性是否存在
解决方案
Sanity默认返回逻辑为:无值的字段不会出现在返回结果中,不会主动返回空字符串、null等空值,因此会出现引用不存在属性的报错,可通过以下3种方式逐层规避:
1. GROQ查询层设置默认值(最推荐)
使用GROQ内置coalesce函数,字段存在且有值时返回原值,字段不存在/为空时返回指定默认值,直接修改查询语句即可:
*[ _type == "property" && slug.current == $pageSlug][0]{ title, propertyType, mainImage, images, saleType, price, bedrooms, bathrooms, slug, id, "description": coalesce(description, ''), agent }
不同类型字段可对应设置匹配的默认值,例如数组字段设置[]、数字字段设置0即可。
2. Props传递阶段补全默认值
使用空值合并运算符,在返回组件Props时补全缺失字段的默认值:
return { props: { title: property.title ?? '', propertyType: property.propertyType ?? '', mainImage: property.mainImage ?? null, images: property.images ?? [], saleType: property.saleType ?? '', price: property.price ?? 0, bedrooms: property.bedrooms ?? 0, bathrooms: property.bathrooms ?? 0, slug: property.slug, id: property.id ?? '', description: property.description ?? '', agent: property.agent ?? null } }
3. 组件接收Props时兜底设置默认值
组件解构入参时直接给每个属性设置默认值,作为最后一层兜底:
const Property = ({ title = '', propertyType = '', mainImage = null, images = [], saleType = '', price = 0, bedrooms = 0, bathrooms = 0, slug, id = '', description = '', agent = null }) => { // 原有组件逻辑 }
三种方式可组合使用,优先从查询层处理无需后续额外兼容,是成本最低的方案。
内容的提问来源于stack exchange,提问作者Gmcintosh
相关产品推荐
相关产品推荐

