我尝试使用typescript和webpack 2在我的项目上启用HMR,但每当我进行更改时,我在日志中看到以下输出,并且存储被重置为其原始值(丢弃状态)
index.js:832 MobX Provider: Provided store 'appStore' has changed. Please avoid replacing stores as the change might not propagate to all children
在加载热更新包之后部分刷新UI,这是好的和预期的但是由于商店失去其状态,UI不是预期的。
什么是在HMR更新中保持mobx商店状态的正确模式?
目前,该coode如下所示:
const uiStore = new UiStore();
const appStore = new AppStore();
function render() {
ReactDOM.render(
<AppContainer>
<Provider appStore={appStore} uiStore={uiStore}><App/></Provider>
</AppContainer>, document.getElementById('root'))
}
const hot = (module as any).hot
if (hot)
hot.accept(() => {
render()
})
render()
问题是,每次热重新加载后,我的索引文件引用了App
组件,这是客户端webpack重新需要的,这会破坏在索引文件中初始化的uiStore
和appStore
对象。将商店声明为window
对象的成员已解决了这个问题。这些商店现在可以在热模块更换中存活下来。
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {AppContainer} from 'react-hot-loader';
import {observable} from 'mobx';
import {Provider} from 'mobx-react';
import {AppStore, UiStore, Stores} from './types/index';
import App from './components/App';
import './index.css';
declare var stores:Stores;
(window as any).stores = (window as any).stores || new Stores(new UiStore(), new AppStore());
function render() {
ReactDOM.render(
<AppContainer>
<App {...stores} />
</AppContainer>, document.getElementById('root'));
}
const hot = (module as any).hot
if (hot)
hot.accept(() => {
render();
})
render();