为什么在nextjs中刷新后所有样式的materialui都会消失?

Mic*_*sai 5 css material-ui server-side-rendering next.js

我从 materialui ( https://material-ui.com/guides/server-rendering/ )的文档中找到了解决方案,但我仍然不知道原因。

  1. 为什么样式在第一次渲染时有效,但在第二次渲染时消失?我知道 SSR 会在每个请求中为客户端生成带有 css 的 html 模板,因此样式应该仍然有效,因为它被注入到 html 模板中。

  2. 在文档中,它提到“在客户端,将在删除服务器端注入的 CSS 之前第二次注入 CSS”。但是,我不知道为什么需要删除它。CSS 被注入到每个请求的 html 模板中,所以它不会导致我的想法出现任何崩溃,以及为什么删除注入的 css 后样式不会消失。

小智 0

在 _app.js 中

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

  return <Component {...pageProps} />
};
Run Code Online (Sandbox Code Playgroud)

然后打开pages文件夹中的_document.js:

import React from 'react';
import { ServerStyleSheets } from "@mui/styles";
import Document, { Html, Main, NextScript, Head } from "next/document";



export default class MyDocument extends Document{

    render(){

        return(
            <Html lang="en">
                <Head></Head>
                <body>
                    <Main/>
                    <NextScript/>
                </body>
            </Html>
        )
    }
}


MyDocument.getInitialProps = async(ctx) =>{
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;
    ctx.renderPage = () =>{
        return originalRenderPage({
            enhanceApp: ( App ) => ( props ) => sheets.collect(<App { ...props} 
 />)
        })
    };
    const initialProps = await Document.getInitialProps( ctx);
    return{
        ...initialProps,
        styles:[
            ...React.Children.toArray(initialProps.styles) , 
            sheets.getStyleElement(),
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)