在webpack应用的入口代码中,实现react相关组件的热重载(hot reload)

前端之家收集整理的这篇文章主要介绍了在webpack应用的入口代码中,实现react相关组件的热重载(hot reload)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

以下是应用的入口文件(main.jsx)的内容,其实现了react组件和reducer的hot reload。

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore,applyMiddleware,combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { Router,hashHistory } from 'react-router';
import { syncHistoryWithStore,routerReducer } from 'react-router-redux'

const getRootReducer = () => {
    var configObj = require( './redux/rootReducer.jsx' ).ReducerConfig
    return combineReducers(
        Object.assign(
            {},configObj,// 补充处理routing信息的reducer
            { routing: routerReducer }
        )
    )
};

const store = createStore(
    getRootReducer(),// 初始state
    {
        "async-items": {
            items: []
        }
    },applyMiddleware( thunk )
);

//Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore( hashHistory,store );
//每次热重载,使用新的Router对象
let RouterKey = 0;
const renderApp = () => {
    var routes = require( './app.jsx' ).RoutesConfig;
    var provider = (
        <Provider store={store}>
            <Router key={RouterKey} history={history} routes={routes} />
        </Provider>
    );

    var AppContainer = null;
    try {
        // 生产环境下,使用IgnorePlugin排除了对react-hot-loader代码的引入
        AppContainer = require( 'react-hot-loader' ).AppContainer;
        console.log( 'has AppContainer' );
    } catch ( e ) { }

    ReactDOM.render(
        AppContainer
            ?
            <AppContainer>
                {provider}
            </AppContainer>
            :
            provider,document.getElementById( 'root' )
    );
};

if ( module.hot ) {
    console.log( 'module.hot enabled' );
    /*
     * 热重载reducer
     * rootReducer.jsx返回的是combineReducers的参数对象
     * rootReducer.jsx是所有reducer的引用的入口
     */
    module.hot.accept( './redux/rootReducer.jsx',() => { store.replaceReducer( getRootReducer() ); }); /* * 热重载组件 * app.jsx返回的是Router的配置对象 * app.jsx是所有react组件的引用的入口,react组件又引用了action */ module.hot.accept( './app.jsx',() => { RouterKey++; renderApp(); }) } renderApp(); @H_404_155@

猜你在找的React相关文章