reactjs - 使用NextJS和Auth0时如何添加共享布局?

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

我已经按照 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 错误。它用于包装 getServerSideProps,而不是页面。

If you wrap your getServerSideProps with WithPageAuthRequired your props object will be augmented with the user property, which will be the user's Claims

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

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

关于reactjs - 使用NextJS和Auth0时如何添加共享布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71136169/

相关文章:

reactjs - 警告 : Expected server HTML to contain a matching <section> in <div>. ---- Next.js/react

javascript - Nextjs Router.push 与 href

javascript - React.js - 正确从 API 加载单个帖子数据

javascript - 添加新页面到reactjs模板

node.js - 将 Google Cloud Function 作为其他 Google API 上的服务帐户进行身份验证

authentication - cUrls 的选项 "-u"

javascript - Next.js 读取 Firestore 数据

javascript - 检测 ReactJS 页面更改

reactjs - 使用 redux-form 创建自定义风格的 Material UI

Asp.net 和 windows 身份验证