javascript - 为什么使用 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 变量。
解决方案
您是否尝试按照with-styled-components
next.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>
);
}
}
推荐阅读
- mysql - 从 Oracle 从 MySQL 数据库中检索数据时出错
- python - Discord.py 多词参数,另一种选择?
- javascript - 循环 JSON,在尝试对 JS 对象进行字符串化时
- python - 带按钮的调光 LED
- python - Keras,我们是否可以将其设置为一直拟合模型,直到损失函数大于一个值或几乎恒定?
- html - 如何为上一个按钮编写jquery函数?
- java - 使用改造将不一致的 JSON 解析为 POJO
- android - 如何修复“npx react-native run-android”错误?
- python - Python for循环求和函数麻烦
- laravel - 磁盘 [google-drive] 没有配置驱动程序