【问题标题】:fetching data from Sanity returns undefined (Next.js + Sanity)从 Sanity 获取数据返回未定义(Next.js + Sanity)
【发布时间】:2021-10-09 14:08:11
【问题描述】:

我有一个页面,我想在其中添加一些实际情况。这些实际情况将首先设置在 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 或省略此值。”

为了获得一组 Actualities,我需要进行哪些更改?

【问题讨论】:

  • 这可能是因为您从 fetch 中得到的是一组实际情况,而不是单个实际情况。返回道具时,您需要相应地更改代码。

标签: reactjs next.js sanity


【解决方案1】:

几件事:

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

【讨论】:

    【解决方案2】:

    将响应包装在数据对象中以序列化并在您的页面道具中调用 {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,
            },
          },
        };
    };
    

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 2021-12-01
      • 1970-01-01
      • 2022-08-04
      • 2022-01-17
      • 2022-12-21
      • 1970-01-01
      • 2022-11-13
      • 2022-06-13
      相关资源
      最近更新 更多