首页 > 解决方案 > 使用 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

标签: reactjsnext.jssanity

解决方案


现在在为今天日期的 apiVersion 提供日期后已修复。

此错误是由使用 GROQ API 的 V1 引起的。设置日期可确保 API 的最新版本。

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)

推荐阅读