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

Next.js页面getStaticProps返回props为undefined问题排查求助

问题根因

你的getStaticProps没有被Next.js识别执行,是因为你导出的是withAuth包裹后的组件,而你的高阶组件只透传了getInitialProps方法,没有透传getStaticProps/getServerSideProps,导致Next.js检测不到页面定义了静态生成方法,自然不会执行它返回props。

解决方案

1. 修改withAuth.tsx透传数据获取方法

在原有的getInitialProps透传逻辑外,新增getStaticProps和getServerSideProps的透传逻辑:

import Login from "../pages/login";
import { Spinner } from "./spinner";

const withAuth = Component => {
  const Auth = (props) => {
    const { isLoggedIn, loading } = props;

    if(loading){
      return (
         <Spinner />
      )
    }
    if (!isLoggedIn) {
       return (
         <Login />
       );
    }

    // 如果用户已登录,返回原组件并传递所有props
    return (
      <Component {...props} />
    );
  };

  // 透传所有Next.js数据获取方法
  if (Component.getInitialProps) {
    Auth.getInitialProps = Component.getInitialProps;
  }
  // 新增透传getStaticProps
  if (Component.getStaticProps) {
    Auth.getStaticProps = Component.getStaticProps;
  }
  // 新增透传getServerSideProps,后续用到时无需再改
  if (Component.getServerSideProps) {
    Auth.getServerSideProps = Component.getServerSideProps;
  }

  return Auth;
};

export default withAuth;

2. 可选优化:移除_app.tsx的getInitialProps

如果你没有全局获取初始数据的强需求,建议删掉_app.tsx里的getInitialProps逻辑,Next.js默认会自动处理所有页面的静态/服务端渲染逻辑,避免不必要的全页服务端渲染开销。

修改后的_app.tsx参考:

import 'tailwindcss/tailwind.css';
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { UserProvider } from '@auth0/nextjs-auth0';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  )
}

export default MyApp

修改完成后重新运行项目,profile.tsx里就能正常拿到getStaticProps返回的users参数了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:18:04