将整个应用程序包装在客户端组件中是否会使应用程序成为客户端呈现的应用程序?

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

我的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 内容不会使整个应用程序客户端呈现吗?我正在努力解决这个问题。请有人详细解释一下为什么layout.js内容仍然在服务器端呈现?

next.js next-auth
1个回答
0
投票

问题:

在next.js中,没有使用客户端组件SessionWrapper包装layout.js内容,从而使整个应用程序客户端呈现?

  • 不,它不会使整个应用程序客户端呈现。
  • NextJS 允许在客户端组件中将作为
    props
    (服务器和客户端组件)传递,但不允许将服务器组件导入到客户端组件中。[1]
  • 这是因为
    props
    可以更改,但是当您导入
    component
    时,它会永久添加到文件中。
  • 服务器组件在处理后由ReactJS添加为
    childrens
    RSC 有效负载 [2].

如何生成包含服务器和客户端组件的页面:

  • 当向服务器发出请求时,首先渲染所有服务器组件,包括嵌套在客户端组件中的组件(如

    props
    )。 [2]

  • 客户端组件不知道子组件 (

    props
    ) 最终将由服务器组件的结果填充。客户端组件的唯一责任是决定子级最终将被放置在哪里。[2]

  • React 将服务器组件呈现为一种特殊的数据格式,称为 React 服务器组件负载(RSC 负载)。[2]

  • RSC 有效负载包含[3]:

    • 服务器组件的结果,

    • 应呈现客户端组件的占位符以及对其 JavaScript 文件的引用,

    • 从服务器组件传递到客户端组件的任何道具

  • Next.js 使用 RSC Payload 和客户端组件 JavaScript 指令在服务器上呈现 HTML。

  • 在客户端,此 HTML 用于立即显示路线的快速非交互式预览 - 这仅适用于初始页面加载。 [2]

  • RSC Payload[3]用于协调客户端和服务器组件树,并更新 DOM。[2]


为什么

layout.js
内容仍然在服务器端呈现?

默认情况下,Next.js 使用服务器组件[4]。

layout.js
默认是服务器组件[5]。

了解更多:

  1. 支持的模式:将服务器组件作为道具传递给客户端组件: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#supported-pattern-passing-server-components -将客户端组件作为道具

  2. 交错服务器和客户端组件:https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#interleaving-server-and-client-components

  3. React 服务器组件有效负载(RSC): https://nextjs.org/docs/app/building-your-application/rendering/server-components#what-is-the-react-server-component-payload -rsc

  4. 嵌套布局(值得了解的部分): https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates#nesting-layouts

  5. 在 Next.js 中使用服务器组件: https://nextjs.org/docs/app/building-your-application/rendering/server-components#using-server-components-in-nextjs

  6. 服务器组件是如何渲染的? :https://nextjs.org/docs/app/building-your-application/rendering/server-components#how-are-server-components-rendered

  7. 客户端组件是如何渲染的? :https://nextjs.org/docs/app/building-your-application/rendering/client-components#how-are-client-components-rendered

  8. 将客户端组件移至树下: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#moving-client-components-down-the-tree

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