[英]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,
},
},
};
};
一些事情:
[0]
,它會返回一個數組,您可以只返回數據,而不管是否是數組。props: {
data: recipe
}
props: {...recipe}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.