【问题标题】:"Element type invalid" when trying to install material ui on next.js project尝试在 next.js 项目上安装材料 ui 时出现“元素类型无效”
【发布时间】:2021-11-08 16:52:53
【问题描述】:

您好,我正在将 Material UI 添加到 Next.js。我遵循了 Next Js git hub 中的示例以及 youtube 教程。我得到的错误是....

错误:元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

这是来自 _document.js 的代码

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';
import theme from '../src/theme';

export default class MyDocument extends Document {
  render() {
    return (
      <Html lang="en">
        <Head>
          {/* PWA primary color */}
          <meta name="theme-color" content={theme.palette.primary.main} />
          <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with server-side generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
  // Resolution order
  //
  // On the server:
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. document.getInitialProps
  // 4. app.render
  // 5. page.render
  // 6. document.render
  //
  // On the server with error:
  // 1. document.getInitialProps
  // 2. app.render
  // 3. page.render
  // 4. document.render
  //
  // On the client
  // 1. app.getInitialProps
  // 2. page.getInitialProps
  // 3. app.render
  // 4. page.render

  // Render app and page and get the context of the page with collected side effects.
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
    });

  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    // Styles fragment is rendered after the app and page rendering finish.
    styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
  };
};

来自错误页面的代码 -

pages/_document.js (57:4) @ Object.ctx.renderPage

  55 | 
  56 |   ctx.renderPage = () =>
> 57 |     originalRenderPage({
     |    ^
  58 |       enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
  59 |     });
  60 | 

enter image description here

【问题讨论】:

    标签: javascript material-ui next.js


    【解决方案1】:

    现在已经解决了。虽然错误显示在 app.js 页面上,但已通过从我的索引页面上的 {link} 导入中删除括号来修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-30
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多