1. install packages

    yarn add mobx mobx-react-lite
  2. in ./tsconfig.json

    1. set compilerOptions.experimentalDecorators = true
    2. sometimes you need to close project and reopenit, otherwise, it might keep waring: Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.ts(1219)
  3. create file src/stores/CounterStore.ts

    import { action, makeObservable, observable } from "mobx";
    
    export class CounterStore {
      constructor() {
        makeObservable(this)
      }
      @observable
      value: number = 0;
    
      @action
      increment() {
        this.value += 1;
      }
    
      @action
      decrement() {
        this.value -= 1;
      }
    }
  4. create file src/stores/index.ts

    import React from "react";
    import { CounterStore } from "./CounterStore"
    
    export const stores = Object.freeze({
      counterStore: new CounterStore()
    })
    
    export const storesContext = React.createContext(stores);
    export const StoresProvider = storesContext.Provider;
  5. create file src/stores/hooks.ts

    import React from 'react'
    import { stores, storesContext } from "./";
    
    export const useStores = () => React.useContext(storesContext);
    
    export const useStore = <T extends keyof typeof stores>(
      store: T
    ): typeof stores[T] => React.useContext(storesContext)[store];
  6. in pages

    import { useEffect } from "react"
    import { useStore } from "../../stores/hooks"
    import { observer } from "mobx-react-lite"
    
    const MyPage = observer(() => {
      const counterStore = useStore('counterStore')
      useEffect(()=>{
        console.log(counterStore?.value)
      }, [counterStore?.value])
      return (
        <div>
          <p><button onClick={()=>counterStore.increment()}>increment</button></p>
          <p><button onClick={()=>counterStore.decrement()}>decrement</button></p>
        </div>
      )
    })
    export default MyPage

    reference: javascript.plainenglish.io/all-you-need-is-mobx-react-lite-47ba0e95e9c8

添加新评论