提交 912e45b5 编写于 作者: J JJ Kasper 提交者: Tim Neutkens

Show error when `router` or `Component` are returned in _app.js (#6487)

* Show error when `router` or `Component` are returned in _app.js
getInitialProps

* Update to only show error in dev mode

* Update packages/next-server/server/render.tsx
Co-Authored-By: Nijjk <22380829+ijjk@users.noreply.github.com>
上级 a169017c
# Can't Override Next Props
#### Why This Error Occurred
In your `pages/_app.js` you returned an object from `getInitialProps` that contained a `router` or `Component` value. These property names are used by Next.js and can not be overwritten.
#### Possible Ways to Fix It
Look in your _app.js component's `getInitialProps` function and make sure neither of these property names are present in the object returned.
### Useful Links
- [The issue this was reported in: #6480](https://github.com/zeit/next.js/issues/6480)
...@@ -212,6 +212,10 @@ export async function renderToHTML( ...@@ -212,6 +212,10 @@ export async function renderToHTML(
return render(renderElementToString, <ErrorDebug error={err} />) return render(renderElementToString, <ErrorDebug error={err} />)
} }
if (dev && (props.router || props.Component)) {
throw new Error(`'router' and 'Component' can not be returned in getInitialProps from _app.js https://err.sh/zeit/next.js/cant-override-next-props.md`)
}
const { const {
App: EnhancedApp, App: EnhancedApp,
Component: EnhancedComponent, Component: EnhancedComponent,
......
import React from 'react'
import App, { Container } from 'next/app'
class MyApp extends App {
static async getInitialProps ({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps, router: () => {} }
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} />
</Container>
)
}
}
export default MyApp
export default () => (
<p>Hello there 👋</p>
)
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import {
renderViaHTTP,
launchApp,
findPort,
killApp
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 30
let server
let appPort
describe('Dynamic require', () => {
beforeAll(async () => {
appPort = await findPort()
server = await launchApp(join(__dirname, '../'), appPort)
})
afterAll(() => killApp(server))
it('should show error when a Next prop is returned in _app.getInitialProps', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/https:\/\/err\.sh\/zeit\/next\.js\/cant-override-next-props\.md/)
})
})
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册