nextjs 和material-ui 的服务器端渲染期间组件闪烁?

Sam*_*mmi 5 reactjs material-ui next.js

我是一名开发人员一年了。我正在使用 next js 和 Material-ui ,没有任何问题。但是最近当我尝试一起使用 next js 和material-ui 时遇到一个问题。这就是闪烁的问题。你面临同样的问题还是只有我面临同样的问题?是材质 ui 还是下一个 js 的问题。那我该如何解决这个问题呢。

这是问题图片 - 请点击此处查看 Gif

这是我的项目 - https://github.com/siamahnaf198/ebuy-ts

这是实时链接 - https://ebuy-ts.vercel.app/

小智 0

在 _document 文件中尝试这个。将 getInitialProps 替换为 _document 文件中的以下内容。

MyDocument.getInitialProps = async (ctx) => {
    const sheets = new ServerStyleSheets();

    const originalRenderPage = ctx.renderPage;

    // You can consider sharing the same emotion cache between all the SSR requests to speed up performance.
    // However, be aware that it can have global side effects.
    const cache = createEmotionCache();
    const { extractCriticalToChunks } = createEmotionServer(cache);

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: (App: any) =>
                function EnhanceApp(props) {
                    return sheets.collect(<App emotionCache={cache} {...props} />);
                },
        });

    const initialProps = await Document.getInitialProps(ctx);
    // This is important. It prevents emotion to render invalid HTML.
    // See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
    const emotionStyles = extractCriticalToChunks(initialProps.html);
    const emotionStyleTags = emotionStyles.styles.map((style) => (
        <style
            data-emotion={`${style.key} ${style.ids.join(' ')}`}
            key={style.key}
            // eslint-disable-next-line react/no-danger
            dangerouslySetInnerHTML={{ __html: style.css }}
        />
    ));

    return {
        ...initialProps,
        styles: [...emotionStyleTags, sheets.getStyleElement()],
    };
};
Run Code Online (Sandbox Code Playgroud)