【发布时间】:2021-11-18 10:10:26
【问题描述】:
我正在使用 sanity.io 和下一个 js。
我需要检查我的数据对象中是否存在属性。
例如,假设我通过查询我创建的所有字段获取数据,但其中一个字段为空。在这个例子中,我有一个字符串类型的字段描述。如果那里没有数据,我希望它返回一个空字符串,但它根本不返回属性,这会导致我的应用程序出错,因为我正在引用不存在的东西。我不知道如何检查这一点并防止错误。
这是我的代码:
import { sanityClient, urlFor } from '../../sanity'
const Property = ({
title,
propertyType,
mainImage,
images,
saleType,
price,
bedrooms,
bathrooms,
slug,
id,
description,
agent
}) => {
console.log(price)
return (
<div className="container mx-auto">
<section>
<h1 className="text-xl font-bold mb-2">{title}</h1>
<div>{propertyType}</div>
</section>
</div>
)
}
export const getServerSideProps = async (pageContext) => {
const pageSlug = pageContext.query.slug
const query = `*[ _type == "property" && slug.current == $pageSlug][0]{
title,
propertyType,
mainImage,
images,
saleType,
price,
bedrooms,
bathrooms,
slug,
id,
description,
agent
}`
const property = await sanityClient.fetch(query, { pageSlug })
if (!property) {
return {
props: null,
notFound: true
}
} else {
return {
props: {
title: property.title,
propertyType: property.propertyType,
mainImage: property.mainImage,
images: property.images,
saleType: property.saleType,
price: property.price,
bedrooms: property.bedrooms,
bathrooms: property.bathrooms,
slug: property.slug,
id: property.id,
description: property.description,
agent: property.agent
}
}
}
}
export default Property
【问题讨论】:
-
您不能将在
props中返回的值默认为空字符串(或您希望该字段的任何默认值),例如description: property.description ?? ''? -
现已修复,请参阅下面的答案。感谢您提供建议。