为什么反应热加载器仅适用于热(模块)(应用程序),并在其他应用程序中复位减速器状态?

时间:2019-06-11 17:32:48

标签: reactjs webpack react-hot-loader

我的项目中有相当老的依赖项,所以我决定更新所有这些依赖项。我遇到的问题与React热加载器有关。现在,我的应用程序组件可以用hot(module)(App)装饰,热加载效果很好。在其他组件/路由中,热加载可以工作,但是会重置所有reducer的状态,因此,由于auth属性已重置且从未更改,因此Web应用程序将重定向到“登录”页面。

应用程序组件:

class App extends Component {
  state={
    loggedIn:false,
    state1:false,
    state2:false,
    state3:false,

  }
  componentDidUpdate(prevProps) {
    console.log('apploggedIn', this.props.loggedIn, prevProps.loggedIn)
    this.props.loggedIn!==prevProps.loggedIn&&this.setState({loggedIn:this.props.loggedIn})

  }
  componentDidMount() {

     // console.log('didmount', this.props)
    this.props.token&&this.props.dispatch(actions.getAttornies(this.props.token))
    this.props.token&&this.props.dispatch(actions.getProviderList(this.props.token)) 




  }
  componentWillMount() {
    this.props.dispatch(actions.isLoggedIn())

  componentWillReceiveProps(nextProps) {

    console.log('nextprops',nextProps)
    if (this.props.token!==nextProps.token) {
      nextProps.token&&nextProps.dispatch(actions.getAttornies(nextProps.token))
      nextProps.token&&nextProps.dispatch(actions.getProviderList(nextProps.token))

    }

  }
  onUnload(){
    this.props.router.push('/')
  }

  onLogin(e) {
    this.props.dispatch(actions.signIn(e.login,e.password))
  }
  render() {
    const { location, children, dispatch, loggedIn, alert } = this.props;
    console.log("AppProps", this.props)


          return <div className="vbox container-fluid">

            <div className="row">
                <section className="hbox stretch" style={{width:'100%', background:'#f3f4f8'}}>

                    <section id="content">
                      <Header
                          router={this.props.history}
                          dispatch={this.props.dispatch}
                          openModal={(e)=>this.openModal(e)}/>

                      <div className="row"
                      >
                      <div className="col-12" style={{minHeight:'90vh'}}>
                        <Switch>
                          <PrivateRoute exact path="/"  component={Startpage} />
                          <Route
                              component={PatientSearch}
                              path="/patient/search"
                          />

                          <PrivateRoute
                              component={Technician}
                              path="/technician"
                          />
                          <Route
                              component={Login}
                              path="/login"
                          />
                          <Route
                              component={Analytics}
                              path="/analytics"
                          />

                          <Route
                              component={Notes}
                              path="/notes"
                          />

                          <Route
                              component={DeliveryReports}
                              path="/delivery_reports"
                          />

                        </Switch>
                      </div>

                      </div>

                    </section>
                </section>
            </div>
          </div>

      }      

  // }
}

const mapStateToProps=(state)=>{
  return {
    loggedIn: state.app.loggedIn,
    token: state.app.token,
    isLoading: state.loading.loading,
    alert:state.alert
  };
}

export default withRouter(connect(mapStateToProps)(hot(module)(App)));

根组件:

const store = configureStore(/* provide initial state if any */)

const PrivateRoute = ({ component: Component, authed, ...rest }) => (
    <Route {...rest} render={(props) => (
        authed === true
            ? <Component {...props} />
            : <Redirect to={{
              pathname: '/login',
              state: { from: props }
            }} />
    )} />
)

class Root extends Component {
  state = {loggedIn:false}




  render() {

    return (
      <Provider store={store}>
        <ConnectedRouter history={history}>
          <Router >
            <App>

            </App>


          </Router>
        </ConnectedRouter>
       </Provider>
    );
  }
}

export default (Root)

最低级组件index.js

import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';
import configureStore from './store/configureStore'
import { AppContainer } from 'react-hot-loader';
const store = configureStore();


const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('wrapperContainer'),
  );
};

render(Root)

if (module.hot) {
  module.hot.accept('./containers/Root', () => {
    const NextRootContainer = require('./containers/Root').default;
    render(NextRootContainer);
  });
}

配置商店部分:

import { createStore, applyMiddleware, combineReducers, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { connectRouter } from 'connected-react-router'

import promiseMiddleware from '../middleware/promiseMiddleware';
import loggerMiddleware from 'redux-logger';
import * as reducers from '../reducers/';
import { reducer as formReducer } from 'redux-form'
import app from '../reducers/app'
import {createBrowserHistory} from "history";

export const history = createBrowserHistory()
const reducer = combineReducers({...reducers.default, router:connectRouter(history), form:formReducer });
const createStoreWithMiddleware = applyMiddleware(
    thunkMiddleware,
    promiseMiddleware
)(createStore);

export default function configureStore(initialState) {
    const store =  createStoreWithMiddleware(
        reducer,
        initialState,
        window.devToolsExtension && window.devToolsExtension()
    );
    if (module.hot) {
        module.hot.accept('../reducers', () => {
            const nextRootReducer = require('../reducers/index').default
            store.replaceReducer(nextRootReducer);
        });
    }
    return store;
}

我真的很抱歉输入这么多代码,但是我真的不知道这里出了什么问题。

1 个答案:

答案 0 :(得分:0)

  • 具有钩子热重载支持的最小React-Hot-loader版本- 4.9.0 ,以下任何内容都不会进行任何更新(除非随后生效)必须重新运行。)
  • 具有挂钩重新排序支持的最小React-Hot-loader版本- 4.11.0 ,如果添加/删除或移动挂钩,则会抛出以下内容。

正如您在RHL的机票中提到的那样-您正在使用4.3.0。