当前位置: 首页 > 文档资料 > Next.js 中文文档 >

自定义 <App>

优质
小牛编辑
124浏览
2023-12-01

Examples
  • Using `_app.js` for layout
  • Using `_app.js` to override `componentDidCatch`

组件来初始化页面。你可以重写它来控制页面初始化,如下面的事:

  • 当页面变化时保持页面布局
  • 当路由变化时保持页面状态
  • 使用componentDidCatch自定义处理错误
  • 注入额外数据到页面里 (如 GraphQL 查询)

重写的话,新建./pages/_app.js文件,重写 App 模块如下所示:

import App, {Container} from 'next/app'
import React from 'react'

export default class MyApp extends App {
  static async getInitialProps ({ Component, router, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return {pageProps}
  }

  render () {
    const {Component, pageProps} = this.props
    return <Container>
      <Component {...pageProps} />
    </Container>
  }
}