为什么使用Nextjs的服务器端渲染样式组件破坏了我的应用程序?

时间:2020-07-01 19:59:38

标签: javascript reactjs next.js styled-components

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

<layout>
    <data>
        <variable name="viewModel" type="MyViewModel2"/>
    </data>

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
      <TextView 
          android:id="@+id/title_one"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="First layout title"/>
      <include
          layout="@layout/reusable_layout"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          app:myText="@{viewModel.mySecondLiveData}"
           />
  </LinearLayout>
</layout>

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

1 个答案:

答案 0 :(得分: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