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

在Next.js中为GetServerSidePropsContext添加自定义属性的问题

解决Next.js + next-redux-wrapper中HOC传递Store的类型问题

问题核心

你已经通过next-redux-wrapper实现了鉴权HOC withAuthRedux,功能正常,但在页面的getServerSideProps中尝试直接访问store时出现类型错误——store不存在于GetServerSidePropsContext中。同时你尝试了嵌套wrapper.getServerSideProps的方案,能访问store但不确定是否合理。

正确的类型定义与HOC改造

你的自定义类型存在继承错误,需要重新定义上下文类型,并调整HOC的参数类型,让页面的getServerSideProps能正确接收包含store的上下文:

1. 修正自定义类型

// 定义包含store的自定义GetServerSideProps上下文
interface CustomGetServerSidePropsContext extends GetServerSidePropsContext {
  store: AppStore; // 直接设为非可选,因为我们确保会传入
}

// 定义HOC接收的函数类型:接收自定义上下文,返回GetServerSidePropsResult
type CustomGetServerSideProps = (ctx: CustomGetServerSidePropsContext) => Promise<GetServerSidePropsResult<any>>;

2. 改造withAuthRedux HOC

调整HOC的参数类型,确保在调用传入的gssp时,把store注入到上下文中:

export function withAuthRedux(gssp: CustomGetServerSideProps): GetServerSideProps {
  return wrapper.getServerSideProps(store => async (ctx: GetServerSidePropsContext) => {
    const auth = await checkUser(ctx);
    if (!auth) {
      return {
        redirect: {
          destination: routes.auth.login,
          statusCode: 302,
        },
      };
    }
    await store.dispatch(setAuthUser(auth.attributes));
    
    // 把store注入到上下文,传给页面的gssp
    return await gssp({ 
      ...ctx, 
      params: { ...ctx.params, currentUser: auth.attributes },
      store // 添加store到上下文
    });
  });
}

3. 页面中正确使用

现在页面的getServerSideProps可以直接访问store,且类型完全正确:

export const getServerSideProps: GetServerSideProps = withAuthRedux(async ({ locale, params, store }) => {
  const auth = params?.currentUser as YourAuthType; // 替换成实际的auth类型,避免any
  
  store.dispatch(setRole(1)); // 类型正确,无报错
  
  return {
    props: {
      // 你的业务props
    },
  };
});

关于嵌套方案的合理性分析

你提到的嵌套方案:

export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(store =>
  withAuthRedux(async ({ locale, params }) => {
    const auth = params?.currentUser as any;

    return {
      props: {
        // ...
      },
    };
  }),
);

这种方案功能上可行,但存在明显缺陷:

  1. 冗余包装:withAuthRedux内部已经调用了wrapper.getServerSideProps,外层再嵌套会重复创建store实例,属于不必要的冗余操作。
  2. 逻辑分散:鉴权逻辑在withAuthRedux内,store访问逻辑在外层回调中,代码拆分不利于维护。
  3. 类型缺失:页面无法直接通过上下文拿到鉴权后的currentUser,仍需手动处理类型转换。

因此更推荐前面的改造方案,既保证类型正确,又让逻辑集中,避免冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 12:52:41