简体   繁体   English

MaterialUI makeStyles 在 NextJS 中刷新时撤消自定义 css

[英]MaterialUI makeStyles undoes custom css upon refresh in NextJS

I am working on a NextJS site that has some custom styling that is being applied via MaterialUI's makeStyles.我正在开发一个 NextJS 站点,该站点具有一些通过 MaterialUI 的 makeStyles 应用的自定义样式。 It works fine on the first load and then undoes all of the custom work on the second.它在第一次加载时工作正常,然后在第二次撤消所有自定义工作。 It seems that it has something to do with the route as the only time that it works is when I first am directed to the page itself.似乎它与路由有关,因为它唯一起作用的时间是当我第一次被定向到页面本身时。 It is happening on 2 different pages one is being directed via href='/login' and the other is being directed via next/router router.push('/register')它发生在 2 个不同的页面上,一个是通过href='/login'引导的,另一个是通过 next/router router.push('/register')引导的

I am assuming that this has to do with the way that Next loads the page?我假设这与 Next 加载页面的方式有关? But I will say that both of these are prerendered pages according to the icon at the bottom right.但是我会说这两个都是根据右下角的图标prerendered pages

import React, {useState} from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { login } from '../store/user/action'
import { useRouter } from 'next/router'

import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';

const style = makeStyles({
    root: {
        marginBottom: '20px',
        textAlign: 'center'
    },
  });


function Signin({login}) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    
    const router = useRouter();

    const clickRegister = (e) => {
        e.preventDefault();
        router.push('/register')
    }

    const classStyle = style();

    return (
        <div className='flex flex-column center m-20 w-750'>
            <h3 className='m-20'>Login</h3>
            <form className='flex flex-column w-750 center' onSubmit={e=>login(e, {email, password})} >
                <TextField
                    className={classStyle.root}
                    required
                    type='email'
                    id="email"
                    label="Email"
                    variant="outlined"
                    onChange={e=>setEmail(e.target.value)}
                />
                <TextField
                    className={classStyle.root}
                    required
                    type='password'
                    id="password"
                    label="Password"
                    variant="outlined"
                    onChange={e=>setPassword(e.target.value)}
                />
                
                <input 
                    type='submit'
                    className='purple-button mt-20 h-3' 
                    onClick={e=>login(e)}
                    value='Login' />
            </form>
            <p>Don't Have an account?</p>
            <form onSubmit='/register'>
                <input value='Register' type='submit' className='flex flex-column w-750 center purple-button h-3' onClick={e=>clickRegister(e)} />
            </form>

        </div>
    )
}



const mapStateToProps = (state) => ({
    email: state.user.email,
    token: state.user.token,
    isLoggedIn: state.user.isLoggedIn,
  })
  
const mapDispatchToProps = (dispatch) => {
    return {
        login: bindActionCreators(login, dispatch),
    }
}
  
export default connect(mapStateToProps, mapDispatchToProps)(Signin)
"dependencies": {
    "@material-ui/core": "4.11.3",
    "axios": "0.21.1",
    "material-ui": "0.20.2",
    "next": "9.4.1",
    "next-redux-wrapper": "^6.0.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "7.1.3",
    "redux": "4.0.5",
    "redux-devtools-extension": "2.13.8",
    "redux-thunk": "2.3.0"
  },

You need additional setup for Material-UI stylesheets in pages/_document.js to support SSR styling.您需要额外设置pages/_document.js中的 Material-UI 样式表以支持 SSR 样式。

If you don't have a custom _document.js yet, create one with the following code:如果您还没有自定义_document.js ,请使用以下代码创建一个:

import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheets } from "@material-ui/core/styles";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheets = new ServerStyleSheets();
    const originalRenderPage = ctx.renderPage;

    ctx.renderPage = () =>
      originalRenderPage({
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />)
      });

    const initialProps = await Document.getInitialProps(ctx);

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [
        ...React.Children.toArray(initialProps.styles),
        sheets.getStyleElement()
      ]
    };
  }

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

export default MyDocument;

For further details check Material-UI official documentation .有关详细信息,请查看Material-UI 官方文档

add these properties to your next.config.js file:将这些属性添加到next.config.js文件中:

const nextConfig = {
  reactStrictMode: true,
  lib: ['es6', 'dom'],
  noImplicitAny: true,
  noImplicitThis: true,
  strictNullChecks: true,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM