【问题标题】:NextJs + Material UI, manually refreshing causes "Warning: Prop `className` did not match. Server: "MuiTypography-root MuiLink" [duplicate]NextJs + Material UI,手动刷新导致“警告:道具`className`不匹配。服务器:“MuiTypography-root MuiLink” [重复]
【发布时间】:2022-02-15 06:35:47
【问题描述】:

我有一个使用 Material UI 的 Next.js 项目,如果我运行服务器并进行更改,热重载工作正常,但如果我手动刷新页面,所有样式都搞砸了,我得到 Warning: Prop className did not match. Server: "MuiTypography-root MuiLink...

这个问题在 Github 上的 Next.js 问题中是 mentioned,并且没有一个建议的解决方案适合我。

【问题讨论】:

    标签: material-ui next.js


    【解决方案1】:

    这是 Next.js 和 @material-ui 的问题。 该问题与 SSR(服务器端渲染)有关,因此您必须取消它并删除服务器端文件。

    第 1 步: 在 pages 文件夹下创建_document.js

    第 2 步: 将此添加到文档文件中

    import { ServerStyleSheets } from '@material-ui/core';
    import Document, { Head, Html, NextScript, Main } from 'next/document';
    import React from 'react';
    
    export default class MyDocument extends Document {
      render() {
        return (
          <Html lang="en">
            <Head></Head>
            <body>
              <Main></Main>
              <NextScript></NextScript>
            </body>
          </Html>
        );
      }
    }
    
    MyDocument.getInitialProps = async (ctx) => {
      const sheets = new ServerStyleSheets();
      const originalRenderPage = ctx.renderPage;
      ctx.renderPage = () => {
        return originalRenderPage({
          enchanceApp: (App) => (props) => sheets.collect(<App {...props} />),
        });
      };
      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: [
          ...React.Children.toArray(initialProps.styles),
          sheets.getStyleElement(),
        ],
      };
    };
    

    第 3 步: 在_app.js里面 在主函数组件中添加这个

      useEffect(() => {
        const jssStyles = document.querySelector('#jss-server-side');
        if (jssStyles) jssStyles.parentElement.removeChild(jssStyles);
      }, []);
    

    重启 Next.js 应用 你就完成了

    【讨论】: