基本方式
对webpack的hot loader机制,基本用法很简单,只需要把hot开启:
1 2 3 4
| devServer: { hotOnly: true, }
|
然后以用module.hot.accept
在根组件做重新渲染就行了:
1 2 3 4 5 6 7 8 9 10 11
| import React from "react"; function App() { return ( <div className='hello'> Hello, webpack! </div> ); };
export default App;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import React from 'react'; import ReactDom from 'react-dom'; import App from './App';
const render = (Component: () => JSX.Element) => { ReactDom.render( <Component />, document.getElementById('app') ); }
render(App);
if (module.hot) { module.hot.accept(['./App'], function () { const App = require('./App').default; render(App); }) }
|
利用react-hot-loader保持组件状态
上面的方式有个问题:组件hot load重新渲染之后状态丢失了,这个时候可以使用react-hot-loader
这个包,用法如下,需要改动几个地方:
1 2 3 4 5 6
| { "plugins": [ "react-hot-loader/babel" ], }
|
1 2 3 4 5 6 7 8 9 10 11 12
| import React from "react"; import { hot } from 'react-hot-loader/root' function App() { return ( <div className='hello'> Hello, webpack! </div> ); };
export default hot(App);
|
1 2 3 4 5 6 7
| { "dependencies": { "react-hot-loader": "^4.13.0", "@hot-loader/react-dom": "^17.0.1" } }
|
1 2 3 4 5 6 7 8
| { resolve: { alias: { 'react-dom': '@hot-loader/react-dom' } } }
|
最后更新时间: