Next.Js 带有样式组件的 React 应用程序。警告:道具`className` 不匹配。服务器:“x” 客户端:“y”

Pau*_*ila 6 javascript reactjs babeljs styled-components next.js

在我的 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);
Run Code Online (Sandbox Code Playgroud)

_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()
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

.babelrc

{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*ing 5

此错误意味着服务器上的某些内容与客户端不同。如果客户端重新渲染,就会发生这种情况。

样式化组件在 React 元素上使用随机 id,当这些元素重新渲染时,它们会在客户端上获得一个新的随机 id。

所以这里的解决方案是专门从服务器获取样式。

来自文档:

基本上你需要添加一个自定义的pages/_document.js(如果你没有的话)。然后复制 styled-components 的逻辑,将服务器端渲染的样式注入到<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() { ..}
}
Run Code Online (Sandbox Code Playgroud)

最后一步(如果错误仍然存​​在)是删除缓存:删除.next文件夹并重新启动服务器

Next 文档中的完整示例代码在这里


小智 1

我也遇到了这个问题,清除缓存/重新启动我的开发服务器似乎已经解决了这个问题。