webpack的devServer里面默认时hot为true,支持热更新的。但是更新了以后状态值会丢失。下面是我的处理方案以及处理时遇到的问题:
一:使用react-hot-loader,版本用的^4.13.0
配置:
- npm install -D react-hot-loader
- webpack的entry入口添加'react-hot-loader/patch',一定要在index配置文件之前
- webpack的plugins添加 new webpack.HotModuleReplacementPlugin()
- .babelrc的plugins添加"react-hot-loader/babel"
在App文件配置:
- 引入import { hot } from 'react-hot-loader/root';
- 导出时 export default hot(App)
存在问题:热更新追踪到index文件以后,redux的store和history因为重复定义会报错,因为Provider不支持重新定义,虽然可以通过存值重新取值的方式,但是最大的问题是外层包裹的connet高阶会有影响
二:推荐使用:react-refresh
配置:
npm install -D @pmmmwh/react-refresh-webpack-plugin react-refresh
参考文章: