mobx入门

281 阅读1分钟

一 安装

  yarn add mobx
  yarn add mobx-react

二 使用

  1. 创建store
  //auth.js
  import {action, observable,makeObservable} from 'mobx';

  class AuthStore{
      //mbox6里面使用observer必须要在store里面写构造函数
      constructor() {
          makeObservable(this)
      }

      @observable values={
          username:'',
          password:''
      };

      @action setUsername=(username)=>{
          this.values.username=username;
      }

      @action setPassword=(password)=>{
          this.values.password=password;
      }

  }

  export default new AuthStore();

  1. 创建useStores函数,用于在函数组件内,获取context对象
  //index.js
  import { createContext, useContext } from 'react';
  import AuthStore from './auth';

  const context = createContext({
      AuthStore
  });

  export const useStores = () => useContext(context);
  1. 使用context
  import {useStores} from '../stores';
  import {observer} from 'mobx-react';
  
  //记得要从mobx-react里面引入observer用来观察组件
  const Component=observer(()=>{
    const {AuthStore} = useStores();
  })
  
  export default Component;

三 配置webpack

  1. 使用装饰器语法报错
  2. 运行命令
  yarn eject
  yarn add @babel/plugin-proposal-decorators
  1. 配置webpack.config.js