mobx的详细使用

慕容玉书
2023-12-01
  • Store.ts
import {makeObservable,observable,action} from 'mobx'
class Store{
    constructor(){
        makeObservable(this,{
            name: observable,
            setName: action
        })
    }
    name = "不写作文的李华"
    setName(){
        this.name = "要写作文的李华"
    }
}
  • App.tsx中
import Store from "xxx/store"
import {observer} from 'mobx-reat'
function App(){
 return(
     <div>
     <p>姓名:{Store.name}</p>
     <button onClick={()=>Store.setName()}>改名字</button>
     </div>
 )
}
export default observer(App)
  • autorun函数
    该函数使用的变量更新后,自动触发这个函数执行
autorun(()=>{
    console,log(Store.name)
})
  • reaction函数
//参数1: data函数,其返回值将会作为第二个函数输入
//参数2: 回调函数
//与autorun不同,reaction在初始化时不会自动运行
reaction(
    () => Store.name,
    ()=>{
        console.log('李华变了')
    }
)
  • 异步操作
//方法1
import { configure } from "mobx"
configure({
    enforceActions: 'never'
})

//方法2
//通过runInAction可以保证所有 异步更新可观察对象的步骤都应该标识为action
import {makeObservable,observable,action} from 'mobx'
class Store{
    constructor(){
        makeObservable(this,{
            name: observable,
            setName: action
        })
    }
    name = "不写作文的李华"
    setName(){
        setTimeout( () => {
            runInAction(() => {
                this.name = "要写作文的李华"
            })
        }
    }
}
  • 合并多个store
  • RootStore.ts
import { useContext, createContext } from‘ react
import Store1 from 'xxx/Store1'
import Store2 from 'xxx/Store2'
cLass RootStore {
    Store1 = Store1
    Store2 = Store2
}
const store = new RootStore()
//createContext传入参数的话,不用提供consumer和provider   
const Context = createContext(store)
export const usestore = () => {
   return useContext(Context) 
}
  • App.tsx中
import usestore from "xxx/RootStore"
import {observer} from 'mobx-reat'
function App(){
    const [store1,store2] = usestore()
 return(
     <div>
     <p>姓名:{Store1.name}</p>
     <p>姓名:{Store2.name}</p>
     </div>
 )
}
export default observer(App)
 类似资料: