React函数组件如何集成mobx

依赖库

"mobx": "^5.15.4",
"mobx-react": "^6.1.8",

定义store

import { observable, computed, action, decorate } from 'mobx';

class AppStore {
    @observable
    public test = 0;

    @action.bound
    public changeTest(newData:number): void {
        this.test = newData;
    }
    
    @action.bound
    public add(): void {
        this.test++;
    }
}

export const appStore = new AppStore();

导出store

import appStore from './appStore.js';
const stores = {
  appStore,
  xxxStore,
  rootStore: {
    appStore
  }
};
/// 默认导出接口
export default stores; 

main引入store

...
import { Provider } from 'mobx-react';
import stores from './store';

ReactDOM.render(
    ,
  document.getElementById('app')
); 

使用store, app.jsx

import { inject, observer } from 'mobx-react';
const App = (props: { appStore: AppStore }) => {
  console.log(props.appStore.test)
}

export default inject('appStore')(observer(App)); 

GitHub demo地址:[https://github.com/hjdshu/rea...]

你可能感兴趣的:(React函数组件如何集成mobx)