簡體   English   中英

從 Sanity 獲取數據返回 undefined (Next.js + Sanity)

[英]fetching data from Sanity returns undefined (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",
        }
    }
}

問題在於獲取數據。

如果我這樣做它會起作用,但只會返回 Sanity 中的第一個現實

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或省略此值。”

我需要更改什么才能獲得一系列 Actualities?

將響應包裝在數據 object 中以序列化並在您的頁面道具中調用 {data} ,如下所示:

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

  const recipe = await client.fetch(query);

  console.log(recipe);

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

一些事情:

  1. 如果您刪除[0] ,它會返回一個數組,您可以只返回數據,而不管是否是數組。
props: {
  data: recipe
}
  1. 如果你想返回帶有 obj 值的單個數據作為多個道具
props: {...recipe}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM