在不改变基本行为的情况下进行最小的 `_app.js` 替换
Minimal `_app.js` replacement without changing base behavior
根据next.jsdocumentation,如果你想自定义<App>
,你必须创建一个pages/_app.js
页面,然后把你的修改放在里面。
不过,在他们的示例中有一些代码,我不知道它的用途是什么:
import React from 'react'
import App, { Container } from 'next/app'
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>
)
}
}
这是最小形式吗?此示例是否更改了初始行为?
换句话说,这段代码是否足以扩展原始应用程序:
import React from 'react'
import App from 'next/app'
export default class MyApp extends App {}
是的,你所拥有的不会改变任何东西,并且是扩展应用程序的最低限度(我已经测试过了)。
我认为他们在文档中包含重写的 getInitialProps
和 render
方法的原因是因为这些可能是您想要添加自定义项和代码的地方如果您要覆盖它们,则需要这些。
例如,如果您覆盖 getInitialProps
但不覆盖 return Component.getInitialProps(ctx)
的结果(在这种情况下,组件是当前页面组件,如 ./pages/index.js
) 那么您的页面组件将不会设置初始道具。
根据next.jsdocumentation,如果你想自定义<App>
,你必须创建一个pages/_app.js
页面,然后把你的修改放在里面。
不过,在他们的示例中有一些代码,我不知道它的用途是什么:
import React from 'react'
import App, { Container } from 'next/app'
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>
)
}
}
这是最小形式吗?此示例是否更改了初始行为?
换句话说,这段代码是否足以扩展原始应用程序:
import React from 'react'
import App from 'next/app'
export default class MyApp extends App {}
是的,你所拥有的不会改变任何东西,并且是扩展应用程序的最低限度(我已经测试过了)。
我认为他们在文档中包含重写的 getInitialProps
和 render
方法的原因是因为这些可能是您想要添加自定义项和代码的地方如果您要覆盖它们,则需要这些。
例如,如果您覆盖 getInitialProps
但不覆盖 return Component.getInitialProps(ctx)
的结果(在这种情况下,组件是当前页面组件,如 ./pages/index.js
) 那么您的页面组件将不会设置初始道具。