首页 > 解决方案 > 为什么使用 Nextjs 的服务器端渲染样式组件会破坏我的应用程序?

问题描述

我有一个需要帮助的错误。每当我访问主页时,我的 Next.js 应用程序都会中断。我不断收到未定义错误的无法读取数据映射。浏览器一直将我指向我的 _document.js 文件,我似乎无法在这里找到错误,因为这个应用程序到目前为止一直运行良好。我将在下面粘贴一些代码。

import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage(App => props => sheet.collectStyles(<App {...props} />));
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }

  render() {
    return (
      <html>
        <Head>{this.props.styleTags}</Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

我的浏览器一直指向const page 变量

标签: javascriptreactjsnext.jsstyled-components

解决方案


您是否尝试按照with-styled-componentsnext.js repo 中的示例进行操作?

我认为尝试这样做可以解决您的问题:

import Document, { Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }

  render() {
    return (
      <html>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

NextJS with-styled-components 示例:with-styled-components


推荐阅读