如何从 RootLayout 检索当前用户会话?

问题描述 投票:0回答:1

我正在尝试处理一个基本的AppBar(使用MUI),我需要知道用户是否登录。

这个 AppBar 是 RootLayout 的一部分(它似乎是整个问题)。

我找不到从 RootLayout 获取当前用户的“内置”方法,并且我没有从文档中找到此用例(可以从页面中找到,但不能从布局中找到)。

我正在使用 next v14 和 aws-amplify v6

我尝试了这个非常简单的代码示例(这个AppBar不存在,但是问题已经出现了)

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";

import { Authenticator } from "@aws-amplify/ui-react";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "test title",
  description: "test descrition",
};

function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <Authenticator>
          {children}
        </Authenticator>
      </body>
    </html>
  );
}

export default RootLayout;

我收到此错误:

 ⨯ ./node_modules/@aws-amplify/ui-react-core/dist/esm/components/FormCore/FormProvider.mjs Attempted import error: 'useForm' is not exported from 'react-hook-form' (imported as 'useForm').

如果我移除包装纸,错误就会消失

next.js aws-amplify
1个回答
0
投票

<Authenticator />
组件需要在客户端组件中使用。因此,您需要创建自己的组件,并在其中包含验证器代码。

请参阅文档了解更多详细信息:

https://docs.amplify.aws/nextjs/build-a-backend/server-side-rendering/nextjs-app-router-server-components/#configure-amplify-client-side

一个例子是:

布局。

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";



const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "test title",
  description: "test descrition",
};

function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <AppWithAuthenticator >{children}</AppWithAuthenticator>
      </body>
    </html>
  );
}

export default RootLayout;

和AppWithAuthenticator.js

'use client'
import { Authenticator } from "@aws-amplify/ui-react";

export default function AppWithAuthenticator({children}) {


  return (
     <Authenticator>
       {children}
     </Authenticator>
  );
}


© www.soinside.com 2019 - 2024. All rights reserved.