react4 使用 react-hot-loader 局部刷新

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

第一步 安装 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 局部刷新

谢谢观看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值