【问题标题】:Next.js custom App getInitialProps TypeErrorNext.js 自定义 App getInitialProps TypeError
【发布时间】:2020-04-24 02:13:00
【问题描述】:

我有一个非常简单的带有 Next JS 入门工具包的应用程序,我正在尝试让它与 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} />;
  }
}

它位于 pages 文件夹的 _app.js 中。

问题是我的索引页也有静态

static async getInitialProps

由于某种原因,它会触发以下错误:

TypeError: Cannot read property 'prototype' of undefined

您可以通过以下 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

重现步骤:

  1. 克隆项目at this branch
  2. npm 安装
  3. npm 运行开发
  4. 导航到 localhost:3000

我将不胜感激!

【问题讨论】:

  • 我在下面添加了一个建议,我认为它可以解决您的问题。如果这是真的,请将答案标记为正确,以防其他人遇到同样的情况:)

标签: javascript reactjs next.js


【解决方案1】:

您需要每次运行各自的ComponentgetInitialProps,而不是App

更改您的 _app.js 以下行:

if (Component.getInitialProps) pageProps = await App.getInitialProps(ctx);

if (Component.getInitialProps) pageProps = await Component.getInitialProps(ctx);

希望这能解决您的问题。

【讨论】:

  • 感谢您的帮助,@Michails!。发布这个问题后,我马上就有了这个想法。更新官方 Next.js 文档会很棒,因为那里使用了 App,这很令人困惑。
猜你喜欢
  • 2019-10-12
  • 2019-10-04
  • 2019-03-01
  • 2021-04-23
  • 1970-01-01
  • 2017-04-14
  • 2020-03-26
  • 2021-03-14
  • 2020-05-31
相关资源
最近更新 更多