You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js + Sanity 项目获取资讯数组返回 undefined 如何解决?

问题原因

你删除查询末尾的[0]后,GROQ语句返回的是所有actuality类型文档组成的数组,但原有代码后续依然按照单个对象的逻辑直接读取headline、publishedAt、body属性,数组本身不存在这些属性,读取结果为undefined。Next.js 不允许getServerSideProps返回的props中存在undefined值,因此抛出序列化错误。

修改方案

1. 调整getServerSideProps逻辑

直接返回完整的资讯数组,不再强行读取单个对象的属性,可按需添加排序规则:

export const getServerSideProps = async (pageContext: any) => {
    // 查询所有actuality文档,默认按发布时间倒序排列
    const query = `*[ _type == "actuality"] | order(publishedAt desc)`;
    const actualities = await client.fetch(query);

    // 若允许无资讯时正常展示空页面,可删除下方判断,直接返回 props: { actualities: actualities ?? [] }
    if (!actualities || actualities.length === 0) return { props: null, notFound: true };
    
    return {
        props: {
            actualities
        },
    };
};

2. 页面组件遍历渲染资讯

页面组件接收资讯数组后,通过遍历渲染所有内容:

// 示例页面组件,需替换为你项目中blockContent的渲染逻辑
export default function AktualityPage({ actualities }) {
  return (
    <div className="aktuality-container">
      <h1>动态资讯</h1>
      {actualities.map((item) => (
        <div key={item._id} className="aktuality-item">
          <h2>{item.headline}</h2>
          <p className="publish-time">{new Date(item.publishedAt).toLocaleDateString('zh-CN')}</p>
          {/* 此处替换为你项目中渲染富文本blockContent的代码,比如<PortableText value={item.body} /> */}
        </div>
      ))}
    </div>
  )
}

内容的提问来源于stack exchange,提问作者user12714160

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 17:00:02