环境配置

image.png

安装

image.png

store配置

1.初始化mobx

image.png

2.链接react

image.png

3.computed计算属性配置

image.png

4.模块化配置

image.png
image.png

案例代码

store/index.js 汇总store

  1. import React from "react"
  2. import countStore from "./CountStore";
  3. import listStore from "./ListStore";
  4. class RootStore {
  5. constructor(){
  6. this.countStore = countStore;
  7. this.listStore = listStore;
  8. }
  9. }
  10. const rootStore = new RootStore()
  11. const context = React.createContext(rootStore)
  12. const useStore = () => React.useContext(context)
  13. export {useStore}

CountStore.js

import {makeAutoObservable} from 'mobx'

class CountStore{
  //数据
  count=10

  constructor() {
    // 响应式
    makeAutoObservable(this)
  }
  //修改
  setCount(num){
    this.count=num
  }
  //getter
  get getCount(){
    return this.count *2
  }
}

const countStore = new CountStore()
export default countStore

ListStore.js

import {makeAutoObservable,computed} from 'mobx'

class ListStore {
  //数据
  List = [1,2,3];

  constructor(){
    makeAutoObservable(this,{
      filterList:computed
    })
  }
  //模拟异步获取数据
  getList(){
    setTimeout(()=>{
      this.List = ['Dan','Amanda','IV']
    },2000)
  }
  //getter
  get filterList(){
    return this.List.map(item=>item+'--')
  }
}
const listStore = new ListStore()
export default listStore