【问题标题】:Why is Server-side rendered styled-components with Nextjs breaking my application?为什么使用 Nextjs 的服务器端渲染样式组件会破坏我的应用程序?
【发布时间】:2020-10-22 08:28:17
【问题描述】:

我有一个需要帮助的错误。每当我访问主页时,我的 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 页面变量

【问题讨论】:

    标签: javascript reactjs next.js styled-components


    【解决方案1】:

    您是否尝试遵循 next.js 存储库中的 with-styled-components 示例?

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

    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 example: with-styled-components

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2023-03-25
      • 2022-12-15
      • 2011-05-06
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多