reactjs - 使用 next.js 检查数据是否存在
问题描述
我正在使用 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
解决方案
现在在为今天日期的 apiVersion 提供日期后已修复。
此错误是由使用 GROQ API 的 V1 引起的。设置日期可确保 API 的最新版本。
以前的代码:
import { createClient, createImageUrlBuilder } from "next-sanity"
const config = {
/**
* Find your project ID and dataset in `sanity.json` in your studio project.
* These are considered “public”, but you can use environment variables
* if you want differ between local dev and production.
*
* https://nextjs.org/docs/basic-features/environment-variables
**/
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || "production",
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
useCdn: process.env.NODE_ENV === "production",
/**
* Set useCdn to `false` if your application require the freshest possible
* data always (potentially slightly slower and a bit more expensive).
* Authenticated request (like preview) will always bypass the CDN
**/
}
/**
* Set up a helper function for generating Image URLs with only the asset reference data in your documents.
* Read more: https://www.sanity.io/docs/image-url
**/
export const urlFor = (source) => createImageUrlBuilder(config).image(source)
// Set up the client for fetching data in the getProps page functions
export const sanityClient = createClient(config)
带有 API 日期的新代码:
import { createClient, createImageUrlBuilder } from "next-sanity"
const config = {
/**
* Find your project ID and dataset in `sanity.json` in your studio project.
* These are considered “public”, but you can use environment variables
* if you want differ between local dev and production.
*
* https://nextjs.org/docs/basic-features/environment-variables
**/
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || "production",
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
useCdn: process.env.NODE_ENV === "production",
apiVersion: '2021-09-25',
/**
* Set useCdn to `false` if your application require the freshest possible
* data always (potentially slightly slower and a bit more expensive).
* Authenticated request (like preview) will always bypass the CDN
**/
}
/**
* Set up a helper function for generating Image URLs with only the asset reference data in your documents.
* Read more: https://www.sanity.io/docs/image-url
**/
export const urlFor = (source) => createImageUrlBuilder(config).image(source)
// Set up the client for fetching data in the getProps page functions
export const sanityClient = createClient(config)
推荐阅读
- sql - SQL Server:从重复项中检索 1 个值
- angular - 每次 iis 服务器发生变化时重新加载渐进式应用程序
- c++ - 具有捆绑属性的 boost::graph metric_tsp_approx 在运行时失败
- c# - .NET Confluent Kafka 消费者内存泄漏
- angularjs - IE11 + Angular 1.5.11 上的奇怪渲染行为
- cassandra - DataStax java.lang.AssertionError:无效的偏移量
- angular2-nativescript - 键盘上方的 Nativescript 移动按钮
- excel - 我们可以从 Excel VBA 连接到 Redshift 吗?
- powershell - 如何在 PowerShell GUI 可执行文件中嵌入图标?
- css - 如何在 Bootstrap 4 中使用 Font Awesome 中的 svg 图标?