第一步 安装 react-hot-loader
npm install react-hot-loader --save第二步 使用
.babelrc
{
"presets": [
[
"env"
],
"stage-0",
"react"
],
"plugins": [
"transform-runtime",
"transform-decorators-legacy",
"react-hot-loader/babel",
[
"import",
{
"libraryName": "antd",
"style": true
}
]
]
}webapck.dev.config.js
{
test: /\.js[x]?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
plugins: ['react-hot-loader/babel'],
}
}
},routers.js
import React from 'react';
import { Switch,BrowserRouter,Router,Route,Link } from 'react-router-dom'
import LoginPage from 'bundle-loader?lazy!./views/view/login';
import IndexPage from 'bundle-loader?lazy!./views/view/index';
import Bundle from '../until/bundle'; // 按需加载
import { hot } from 'react-hot-loader'
const supportsHistory = 'pushState' in window.history; // 不支持 HTML5 history API 的浏览器中使用
const Login = () =>(
<Bundle load={LoginPage}>
{(LoginPage) => <LoginPage/>}
</Bundle>
)
const Index = () =>(
<Bundle load={IndexPage}>
{(IndexPage) => <IndexPage/>}
</Bundle>
)
class Routers extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<BrowserRouter forceRefresh={!supportsHistory}>
<div>
<Route path='/' component={Index}></Route>
<Route path='/login' component={Login}></Route>
<Route path='/index' component={Index}></Route>
</div>
{/*<Route path='/base' component={Base}></Route>*/}
</BrowserRouter>
)
}
}
export default hot(module)(Routers) // react 局部刷新谢谢观看。

本文介绍了如何在React应用中使用react-hot-loader进行局部刷新。首先讲解了安装react-hot-loader的步骤,然后详细阐述了配置.babelrc、webpack.dev.config.js以及在routers.js中使用该库的方法,实现组件热替换,提高开发效率。
488

被折叠的 条评论
为什么被折叠?



