首页 > 解决方案 > 从 Sanity 获取数据返回未定义(Next.js + Sanity)

问题描述

我有一个页面,我想在其中添加一些实际情况。这些实际情况将首先在 Sanity 中设置,然后通过 Next.js 获取。

我的理智模式

export default{
    name:"actuality",
    title:"Aktuality",
    type:"document",
    fields:[
        {
            name:"headline",
            title:"Nadpis",
            type:"string"
        },
        {
            name:"publishedAt",
            title:"Datum zveřejnění",
            type:"datetime"
        },
        {
            name:"body",
            title:"Text",
            type:"blockContent"
        }
    ],

    preview:{
        select:{
            title:"headline",
        }
    }
}

问题在于获取数据。

如果我这样做,它会起作用,但只会返回理智中的第一个现实

export const getServerSideProps = async (pageContext: any) => {
    const query = `*[ _type == "actuality"][0]`;

    const recipe = await client.fetch(query);

    console.log(recipe);

    if (!recipe) return { props: null, notFound: true };
    else
        return {
            props: {
                headline: recipe.headline,
                publishedAt: recipe.publishedAt,
                body: recipe.body,
            },
        };

};

但是如果我删除 [0] 它会抛出错误:“原因:undefined无法序列化为 JSON。请使用null或省略此值。”

为了获得一系列实际情况,我需要更改什么?

标签: reactjsnext.jssanity

解决方案


一些事情:

  1. 如果你删除它会返回一个数组[0],你可以只返回数据,不管数组与否。
props: {
  data: recipe
}
  1. 如果您想返回带有 obj 值的单个数据作为多个道具
props: {...recipe}

推荐阅读