在 NextJS 中不会用
layout.js
包装 SessionWrapper
内容
这是一个客户端组件,使整个应用程序成为客户端
渲染了?
请有人详细解释一下,为什么
layout.js
内容仍然在服务器端渲染?
layout.js 文件:
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import SessionWrapper from "@/components/SessionWrapper";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<SessionWrapper>
<Navbar />
<div className="text-white min-h-screen relative">
{children}
</div>
<Footer />
</SessionWrapper>
</body>
</html>
);
}
SessionWrapper 组件:
"use client"
import { SessionProvider } from "next-auth/react"
export default function SessionWrapper({children}) {
return (
<SessionProvider>
{children}
</SessionProvider>
)
}
问题:
在next.js中,没有使用客户端组件SessionWrapper包装layout.js内容,从而使整个应用程序客户端呈现?
props
(服务器和客户端组件)传递,但不允许将服务器组件导入到客户端组件中。[1]props
可以更改,但是当您导入 component
时,它会永久添加到文件中。childrens
RSC 有效负载 [2].如何生成包含服务器和客户端组件的页面:
当向服务器发出请求时,首先渲染所有服务器组件,包括嵌套在客户端组件中的组件(如
props
)。 [2]
客户端组件不知道子组件 (
props
) 最终将由服务器组件的结果填充。客户端组件的唯一责任是决定子级最终将被放置在哪里。[2]
React 将服务器组件呈现为一种特殊的数据格式,称为 React 服务器组件负载(RSC 负载)。[2]
RSC 有效负载包含[3]:
服务器组件的结果,
应呈现客户端组件的占位符以及对其 JavaScript 文件的引用,
从服务器组件传递到客户端组件的任何道具
Next.js 使用 RSC Payload 和客户端组件 JavaScript 指令在服务器上呈现 HTML。
在客户端,此 HTML 用于立即显示路线的快速非交互式预览 - 这仅适用于初始页面加载。 [2]
为什么
内容仍然在服务器端呈现?layout.js
默认情况下,Next.js 使用服务器组件[4]。
layout.js
默认是服务器组件[5]。
进一步: 如果您想在前端看到 RSC 收到
您可以在
RSC
中看到Network tab
,
对于前。我在 folder
目录中创建了一个 app
作为 about
,其中 page.js
只包含一个 div
<div>Dummy Content</div>
然后在浏览器中导航至
http://localhost:3000/about
打开Network tab
你会看到名字about
,点击它就可以看到
Headers > Response Headers > Vary : RSC...
现在还点击
Preview
,它将向您显示服务器渲染的 HTML。
如果你还在其中添加了一个客户端组件
about
page.js,它将只显示基本的HTML。
了解更多:
支持的模式:将服务器组件作为道具传递给客户端组件: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#supported-pattern-passing-server-components -将客户端组件作为道具
React 服务器组件有效负载(RSC): https://nextjs.org/docs/app/building-your-application/rendering/server-components#what-is-the-react-server-component-payload -rsc
嵌套布局(值得了解的部分): https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates#nesting-layouts
在 Next.js 中使用服务器组件: https://nextjs.org/docs/app/building-your-application/rendering/server-components#using-server-components-in-nextjs
服务器组件是如何渲染的? :https://nextjs.org/docs/app/building-your-application/rendering/server-components#how-are-server-components-rendered
客户端组件是如何渲染的? :https://nextjs.org/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered