依赖库
"mobx": "^5.15.4",
"mobx-react": "^6.1.8",
定义store
import { observable, computed, action, decorate } from 'mobx';
class appStore {
// state
appName = 'app1';
appBaseData = {};
// getter
get skinWindow() {
return {
width: this.appName,
height: this.appBaseData
};
}
// action
setAppAuto(payload) {
this.appIsAuto = payload;
}
}
decorate(appStore, {
mainWindowHandle: observable,
contentWindowHandle: observable,
skinWindow: computed,
setAppAuto: action
});
export default appStore;
导出store
import AppStore from './appStore.js';
let appStore = new AppStore();
const stores = {
appStore,
eventStore,
rootStore: {
appStore
}
};
/// 默认导出接口
export default stores;
main引入store
...
import { Provider } from 'mobx-react';
import stores from './store';
ReactDOM.render(
<Provider {...stores}>
<App />
</Provider>,
document.getElementById('app')
);
使用store, app.jsx
import { inject, observer } from 'mobx-react';
const App = ({ appStore }) => {
console.log(appStore.appName)
}
export default inject('appStore')(observer(App));
GitHub demo地址:https://github.com/hjdshu/react-mobx
网友评论