英文:
Next.js custom App getInitialProps TypeError
问题
我有一个使用Next JS起始工具包的相当简单的应用程序,我正在尝试按照这里的文档上指定的自定义应用程序进行工作:
class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
const isAuthenticated = await (process.browser
? Auth0Client.clientAuth()
: Auth0Client.serverAuth(ctx.req));
console.log("isAuthenticated: ", isAuthenticated);
if (Component.getInitialProps) pageProps = await App.getInitialProps(ctx);
const auth = { isAuthenticated };
return { pageProps, auth };
}
render() {
const { Component } = this.props;
return <Component auth={this.props.auth} />;
}
}
它被放置在pages文件夹的_app.js中。
问题是我的index页面也有静态的getInitialProps
,出现以下错误:
TypeError: 无法读取未定义的属性 'prototype'
您可以通过此URL查看我的_app.js文件:
https://github.com/bodrovphone/next-app/blob/breakingPoint/pages/_app.js
和index.js文件的URL在这里:
https://github.com/bodrovphone/next-app/blob/breakingPoint/pages/index.js
重现步骤:
- 克隆项目在此分支
- npm install
- npm run dev
- 导航到localhost:3000
我将不胜感激任何帮助!
英文:
I have quite a simple app with Next JS starter kit and I am trying to get it work with custom app as specified on the docs here:
class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {};
const isAuthenticated = await (process.browser
? Auth0Client.clientAuth()
: Auth0Client.serverAuth(ctx.req));
console.log("isAuthenticated: ", isAuthenticated);
if (Component.getInitialProps) pageProps = await App.getInitialProps(ctx);
const auth = { isAuthenticated };
return { pageProps, auth };
}
render() {
const { Component } = this.props;
return <Component auth={this.props.auth} />;
}
}
It is placed inside _app.js of pages folder.
The thing is that my index page also has static
static async getInitialProps
and it triggers the following error for some reason:
TypeError: Cannot read property 'prototype' of undefined
You can see my _app.js file here by this URL:
https://github.com/bodrovphone/next-app/blob/breakingPoint/pages/_app.js
And index.js file URL here:
https://github.com/bodrovphone/next-app/blob/breakingPoint/pages/index.js
Steps to reproduce:
- clone the project at this branch
- npm install
- npm run dev
- navigate to localhost:3000
I would appreciate any assistance!
答案1
得分: 2
更改您的 _app.js 文件中的以下行:
if (Component.getInitialProps) pageProps = await App.getInitialProps(ctx);
为
if (Component.getInitialProps) pageProps = await Component.getInitialProps(ctx);
我希望这解决了您的问题。
英文:
You need to run the respective Component
's getInitialProps
each time, and not the App
's.
Change your _app.js following line:
if (Component.getInitialProps) pageProps = await App.getInitialProps(ctx);
to
if (Component.getInitialProps) pageProps = await Component.getInitialProps(ctx);
I hope this solves your issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论