使用@material-ui/core 和 NextJS/React 时的 FOUC

FOUC when using @material-ui/core with NextJS/React

我的简单 NextJS 页面是这样的(结果可以在 https://www.schandillia.com/ 查看):

/* eslint-disable no-unused-vars */

import React, { PureComponent, Fragment } from 'react';
import Head from 'next/head';
import compose from 'recompose/compose';
import Layout from '../components/Layout';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    textAlign: 'center',
    paddingTop: 200,
  },
  p: {
    textTransform: 'uppercase',
    color: 'red',
  },
};

class Index extends PureComponent {
  render() {
    const { classes } = this.props;
    const title = 'Project Proost';
    const description = 'This is the description for the homepage';
    return (
      <Fragment>
        <Head>
          <title>{ title }</title>
          <meta name="description" content={description} key="description" />
        </Head>
        <Layout>
          <p className={classes.p}>amit</p>
          <Button variant="contained" color="secondary">
            Secondary
          </Button>
        </Layout>
      </Fragment>
    );
  }
}

export default withStyles(styles)(Index);

我正在从 @material-ui/core 库中导入一堆组件来设计我的项目。我还有一个分配给 style 常量的本地样式定义。

这里似乎发生的是我的样式没有在服务器上呈现,这就是加载时提供的文件是 sans 样式的原因。然后 CSS 由客户端代码呈现。结果,一闪而过的无样式内容持续了将近一秒钟,足够长以引起注意。

有什么办法可以解决这个问题吗?整个代码库可供参考 https://github.com/amitschandillia/proost/tree/master/web.

我 运行 在尝试使用 material-ui 制作我的应用程序的生产 build 时遇到了类似的问题。我设法通过添加这样的 JSS Provider 来解决:

import JssProvider from "react-jss/lib/JssProvider";

class App extends Component {
  render() {
    <JssProvider>
      *the rest of your material-ui components*
    </JssProvider>
  }
}

这是解决方案 - https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js .

基本上,您需要做的就是将服务器端 class 名称与客户端同步。上面的 link 显示了解决该问题需要执行的操作。