自定义应用 (Custom App)
Next.js 使用 App
组件来初始化页面。您可以重写它并控制页面初始化,实现以下功能:
- 在页面切换时创建共享布局
- 向页面注入额外数据
- 添加全局 CSS
使用方法
要重写默认的 App
,请按照以下示例创建 pages/_app
文件:
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
Component
属性是当前活动的 page
,因此当您在路由之间导航时,Component
会切换为新的 page
。因此,您传递给 Component
的任何属性都会被该 page
接收。
pageProps
是一个对象,包含通过我们的数据获取方法为页面预加载的初始属性,如果没有则为一个空对象。
须知
- 如果您的应用正在运行且添加了自定义
App
,则需要重启开发服务器。仅当之前不存在pages/_app.js
时才需要此操作。App
不支持 Next.js 的数据获取方法,如getStaticProps
或getServerSideProps
。
在 App
中使用 getInitialProps
在 App
中使用 getInitialProps
会禁用未使用 getStaticProps
的页面的自动静态优化 (Automatic Static Optimization)。
我们不推荐使用这种模式。 相反,建议考虑逐步采用 App Router,它可以更轻松地为页面和布局获取数据。
import App, { AppContext, AppInitialProps, AppProps } from 'next/app'
type AppOwnProps = { example: string }
export default function MyApp({
Component,
pageProps,
example,
}: AppProps & AppOwnProps) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (
context: AppContext
): Promise<AppOwnProps & AppInitialProps> => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}
import App from 'next/app'
export default function MyApp({ Component, pageProps, example }) {
return (
<>
<p>Data: {example}</p>
<Component {...pageProps} />
</>
)
}
MyApp.getInitialProps = async (context) => {
const ctx = await App.getInitialProps(context)
return { ...ctx, example: 'data' }
}