The installation

  yarn add mobx
  yarn add mobx-react
Copy the code

2 use

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

  class AuthStore{
      // To use the observer in mbox6, you must write the constructor in the 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();

Copy the code
  1. Create a useStores function that retrieves the context object within the function component
  //index.js
  import { createContext, useContext } from 'react';
  import AuthStore from './auth';

  const context = createContext({
      AuthStore
  });

  export const useStores = () = > useContext(context);
Copy the code
  1. Use the context
  import {useStores} from '.. /stores';
  import {observer} from 'mobx-react';
  
  // Remember to import an observer from mobx-React to observe components
  const Component=observer(() = >{
    const {AuthStore} = useStores();
  })
  
  export default Component;
Copy the code

Three configuration webpack

  1. Error using decorator syntax

2. Run commands

  yarn eject
  yarn add @babel/plugin-proposal-decorators
Copy the code
  1. Configuration webpack. Config. Js