英文:
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.js
和 pages/_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 "use client"
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
"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>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论