introduction
Next.js 使用App组件来初始化页面,你能够覆盖App组件并控制页面的初始化 … 这样你可以做一些很吓人的事情,例如:
- 页面切换之间保持布局的持久性
- 切换页面时保证状态(state)
- 使用
componentDidCatch自定义错误处理 - 向页面(pages) 注入额外的数据
- 添加全局CSS
要覆盖默认的App,首先要创建.pages/_app.js文件,如下:
// import App from 'next/app'function MyApp({ Component, pageProps }) {return <Component {...pageProps} />}// Only uncomment this method if you have blocking data requirements for// every single page in your application. This disables the ability to// perform automatic static optimization, causing every page in your app to// be server-side rendered.//// MyApp.getInitialProps = async (appContext) => {// // calls page's `getInitialProps` and fills `appProps.pageProps`// const appProps = await App.getInitialProps(appContext);//// return { ...appProps }// }export default MyApp
Component即当前的page,因此当你在路由之间切换的时候,Component将会 更新为新的page,因此你传递给Component的任何属性都会被page接收到 …
pageProps是带有初始属性的对象,该初始化属性由我们某个数据获取方法预先加载到你的页面中(否则它将是一个空对象) …
注意事项
如果你对App组件进行自定义的时候你的应用程序正在运行中,那么你需要重新启动开发服务器才能够使它生效,仅当pages/_app.js不存在时才需要重启开发服务器 …
- 在
App中添加自定义的getInitialProps将导致不支持静态生成的页面禁用自动静态优化功能 … - 在自定义的
App添加getInitialProps,必须添加import App from 'next/app',在getInitialProps内部调用App.getInitialProps(appContext)并将返回的对象合并到返回值中 … - 当前
App不支持Next.js数据获取方法(例如getStaticProps以及getServerSideProps)
Ts
如果使用的是TypeScript,查看
