Next.js app folder: is there some "entry point"? A direct replacement for _app.tsx and _document.js?

huangapple go评论79阅读模式
英文:

Next.js app folder: is there some "entry point"? A direct replacement for _app.tsx and _document.js?

问题

我以前有一个自定义的 _app.tsx 文件,用于为我的应用进行一些初始化操作:
useEffect(() => void defineCustomElements(), []); 它加载了自定义元素/网络组件并确保它们可以被水合。

现在,我应该把这个效果放在哪里,考虑到应用路由没有一个 "全局" 的 _app.tsx,而且还采用了 "服务器组件优先" 的方式?

英文:

Previously I had a custom _app.tsx that did some bootstrapping for my application:
useEffect(() => void defineCustomElements(), []); It loaded custom elements/web components and made sure they can be hydrated.

Where should I put this effect now with the app router that 1. doesn't have a "global" _app.tsx and secondly is "server component first"?

答案1

得分: 6

升级指南页面上,他们说:“pages/_app.jspages/_document.js 已被替换为一个名为 app/layout.js 的根布局”。

因此,在您的情况下,您可以将您的逻辑放在那里,并在顶部使用 use client 使其成为客户端组件,例如在其中使用 useEffect 来实现客户端交互。

但如果您不希望您的根布局成为客户端组件,您可以像下面这样做,例如,使用一个单独的组件:

// DefineCustomElements.js

"use client";

export default function DefineCustomElements() {
  useEffect(() => defineCustomElements(), []);

  return <></>;
}
// app/layout.js

import DefineCustomElements from "./DefineCustomElements";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <DefineCustomElements />
        {children}
      </body>
    </html>
  );
}
英文:

On the Upgrade Guide page, they say "pages/_app.js and pages/_document.js have been replaced with a single app/layout.js root layout".

So in your case, you can put your logic there and make it a client component with &quot;use client&quot; at the top if you want client interactivities like a useEffect in it.

But say you don't want your root layout to be a client component, you could do as below, for example, using a separate component:

// DefineCustomElements.js

&quot;use client&quot;;

export default function DefineCustomElements() {
  useEffect(() =&gt; defineCustomElements(), []);

  return &lt;&gt;&lt;/&gt;;
}

// app/layout.js

import DefineCustomElements from &quot;./DefineCustomElements&quot;;

export default function RootLayout({ children }) {
  return (
    &lt;html lang=&quot;en&quot;&gt;
      &lt;body&gt;
        &lt;DefineCustomElements /&gt;
        {children}
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

huangapple
  • 本文由 发表于 2023年4月6日 23:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定