在我的NextJS React应用程序中,当我更改代码中的某些内容时,HMR可以工作并显示正确的更新,但是如果刷新页面,则会再次出现此错误。这发生在开发人员模式下。 注意到哪里有很多出现此错误的主题,请整日尝试所有不同的配置设置。
请帮助我摆脱错误。
错误:
警告:道具
className
不匹配。服务器:“ sc-cBoprd hjrjKw” 客户:“ sc-iCoHVE daxLeG”
使用“ babel-plugin-styled-components”:“ 1.11.1”
可能与此问题相关的文件
_App.tsx
function MyApp({ Component, pageProps, mainController }) {
return (
<ConfigurationProvider configuration={configuration}>
<ThemeProvider theme={mainController.getTheme()}>
<Normalize />
<Font />
<Component {...pageProps} controller={mainController} />
</ThemeProvider>
</ConfigurationProvider>
);
}
export default appControllerContext(MyApp);
_document.tsx
import Document 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()
}
}
}
.babelrc
{
"presets": [
"next/babel"
],
"plugins": [
[
"babel-plugin-styled-components",
{
"ssr": true,
"displayName": true,
"preprocess": false
}
]
]
}
答案 0 :(得分:1)
此错误意味着服务器上的某些内容与客户端不同。 如果客户端重新渲染,就会发生这种情况。
样式化组件在 React 元素上使用随机 id,当这些元素被重新渲染时,它们会在客户端获得一个新的随机 id
所以这里的解决方案是专门从服务器获取样式。
<块引用>基本上你需要添加一个自定义页面/_document.js(如果你没有
有一个)。然后复制样式组件的逻辑以注入
服务器端呈现的样式到 <head>
要解决这个问题,您的文档组件中需要这样的东西:
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() { ..}
}
最后一步(如果错误仍然存在)是删除缓存:
删除.next
文件夹并重启服务器
Next 文档中的完整示例代码是 from the docs:
答案 1 :(得分:0)
我也遇到了这个问题,到目前为止,清除缓存/重新启动开发服务器似乎已解决了该问题。
答案 2 :(得分:0)
最后,唯一可行的解决方案是将.babelrc.json重命名为babel.config.json。如果仍然有人遇到此错误,我在此留下如何解决solution
的参考。