HMR(热模块更换)可以更新当前模块吗?

时间:2018-11-22 20:04:26

标签: reactjs webpack-dev-server webpack-hmr

HMR可以更新当前模块吗?我对此进行了测试,但似乎无法正常工作。有人可以详细解释为什么这行不通吗?是否要求始终有更高的模块来更新替换模块。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './App';

import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';

const styles = theme => ({});

class UserCreate extends Component {

    state = {
        spacing: '8',
    };

    render() {
        const { classes } = this.props;
        const { spacing }  = this.state;
        return (<Typography>User create says hello</Typography>)
    }
}


UserCreate.propTypes = { 
  "classes": PropTypes.object.isRequired
}

const UserCreateWithStyles = withStyles(styles)(UserCreate)

export default UserCreateWithStyles

const element = document.getElementById('root');

export const render = (Component) => { 
        ReactDOM.render(<App><Component/></App>,element);
    }

if (module.hot) {
    module.hot.accept("./UserCreate", () => {
        const NextContainer = require("./UserCreate").default;
        render(NextContainer);
      });
}

下面是HMR的常规实现。创建一个高阶模块,通过检查module.hot

来更新更改的模块。

app.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import UserCreate from './UserCreate';

const element = document.getElementById('root');


export const render = (Component) => { 
        ReactDOM.render(<Component>,element);
}

if (module.hot) {
    module.hot.accept("./UserCreate", () => {
        const NextContainer = require("./UserCreate").default;
        render(NextContainer);
    });
}

0 个答案:

没有答案