美文网首页
mobx如何在react 函数式组件(hooks)中使用

mobx如何在react 函数式组件(hooks)中使用

作者: JakeBless | 来源:发表于2020-07-20 11:52 被阅读0次

    依赖库

    "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

    相关文章

      网友评论

          本文标题:mobx如何在react 函数式组件(hooks)中使用

          本文链接:https://www.haomeiwen.com/subject/ietvahtx.html