【问题标题】:How to add a shared layout when using NextJS and Auth0?使用 NextJS 和 Auth0 时如何添加共享布局?
【发布时间】:2022-03-11 11:07:09
【问题描述】:

我已按照 Next 文档设置布局,效果很好。但是,NextJS Auth0 SDK 有一个 withPageAuthRequired 包装,打破了这种模式。

我使用的模式来自这些docs。例如,这里是一个页面组件:

function Page(): ReactElement {
  return <DashboardLayout>"Code Detail Page"</DashboardLayout>
}

Page.getLayout = function getLayout(page: ReactElement) {
  return <DashboardLayout>{page}</DashboardLayout>
}

export default withPageAuthRequired(Page)

然后在我的_app.tsx:

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const getLayout = Component.getLayout || ((page) => page)

  return (
    <UserProvider>
        {getLayout(<Component {...pageProps} />)}
    </UserProvider>
  )
}

export default MyApp

我遇到的问题是我的布局不再被拉出,我假设这是因为 Auth0 包装器。

如果我执行以下操作,我可以渲染布局,但我需要在 AuthWrapper.getLayout 分配之前添加一个 // @ts-ignore

const AuthWrapper = withPageAuthRequired(Page)

AuthWrapper.getLayout = function getLayout(page: ReactElement) {
  return <DashboardLayout>{page}</DashboardLayout>
}
export default AuthWrapper

是否有另一种使用这种模式的布局的替代方法,不需要将// @ts-ignore 添加到我所有经过身份验证的页面?

【问题讨论】:

  • 不幸的是,看起来withPageAuthRequired() 的返回类型是一个预计会在服务器端调用的函数,而该函数的返回类型是一个 Promise。下次我在做这个项目时,我会按照这些思路尝试一些事情,看看我是否可以在没有任何 TS hack 的情况下让它工作
  • 您可以扩展withPageAuthRequired 的类型,使其也包括getLayout

标签: reactjs authentication next.js server-side-rendering auth0


【解决方案1】:

我认为您使用 withPageAuthRequired 错误。它用于包装getServerSideProps,而不是页面。

如果您使用 WithPageAuthRequired 包装您的 getServerSideProps props 对象将增加 user 属性,这将是 用户声明

export const getServerSideProps = withPageAuthRequired({
  getServerSideProps: async ({ req, res }) => {
    const auth0User = getSession(req, res);
    ... add logic here

    return {
      props: {
        myProp,
      },
    };
  },
});

【讨论】:

  • 只是想分享一个更新,说这确实是问题所在。一旦我解决了这个问题,与 Typescript 相关的一切都很愉快
猜你喜欢
  • 2020-02-24
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 2022-12-05
相关资源
最近更新 更多