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

TypeScript中getServerSideProps返回中间值undefined致应用崩溃问题

问题根因

  • 服务端调用client.query时返回结果不存在loading字段:loading是useQuery等客户端hook专属的前端请求状态,服务端调用client.query会等待请求结束后才返回结果,你解构的loading本身就是undefined,是导致崩溃的核心原因。
  • TypeScript校验不通过是因为你没有为Home组件的入参props定义类型,TS无法识别data等字段的类型和存在性。
  • getServerSideProps运行在服务端,不需要传递loading状态到组件:服务端渲染完成后页面直接返回渲染结果,不存在客户端请求的加载过程。

修复方案

首先删除无用的loading字段,为组件props定义对应类型,按需捕获请求异常即可,参考代码如下:

// 先根据你实际的GraphQL schema定义数据类型,以下为示例
type VideoItem = {
  id: string;
  title: string;
  // 补充你实际的字段
}

type HomeProps = {
  error: Error | null;
  data: {
    allVideos: VideoItem[] // 和GET_ALL_VIDEOS的返回结构对应
  }
}

export default function Home({ data, error }: HomeProps):JSX.Element {
  // 优先处理错误场景
  if (error) {
    return <div>页面加载出错,请刷新重试</div>
  }

  return (
    <div>
      <div className="flex flex-col  bg-gray-800 w-full items-center pb-10 ">
        <div className="flex flex-col max-w-screen-xl w-full ">
          <div className="flex flex-col text-white  w-full p-10 ">
            <div className="flex justify-between gap-10  ">
              <h1 className=" uppercase font-medium">
                <b>muhammad ali </b>
                vs
                <b> joe frazier</b>
              </h1>
              <p>New York, 1971 | 48:38</p>
            </div>
            <div className="w-full ">
              <HomeVideo />
            </div>
          </div>
        </div>
      
    </div>
  );
}

export async function getServerSideProps() {
  try {
    const { error, data } = await client.query({
      query: GET_ALL_VIDEOS,
    });
    return {
      props: {
        error: error || null,
        data: data,
      },
    };
  } catch (err) {
    // 捕获网络等异常,避免服务端渲染直接失败
    return {
      props: {
        error: err as Error || null,
        data: null
      }
    }
  }
}

补充说明

如果你的业务确实需要客户端加载状态,应该直接在组件层使用useQuery实现,不要在getServerSideProps中获取不存在的loading字段。如果需要跨多层组件传递data,可以在getServerSideProps拿到数据后,结合React Context或者props逐层传递,TS层面只要定义好对应类型就不会出现校验报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:36:05