MobX 是一個(gè)身經(jīng)百戰(zhàn)的庫(kù),它通過運(yùn)用透明的函數(shù)式響應(yīng)編程(Transparent Functional Reactive Programming,TFRP)使?fàn)顟B(tài)管理變得簡(jiǎn)單和可擴(kuò)展。官網(wǎng)地址:關(guān)于 MobX | MobX中文文檔 | MobX中文網(wǎng)
安裝依賴
mobx-react-lite是一個(gè)mobx和react建立鏈接的依賴庫(kù),也必須安裝才可以使用
yarn add mobx
yarn add mobx-react-lite
創(chuàng)建一個(gè)或者多個(gè)store
并使用store/index.js統(tǒng)一管理,這樣以后只需要使用統(tǒng)一的一種方式就可以了
CountStore.js:一個(gè)存儲(chǔ)數(shù)據(jù)的store
import { makeAutoObservable } from "mobx"
class CountStore {
count = 0
constructor() {
makeAutoObservable(this)
}
addCount = () => {
this.count++
}
}
export default CountStore
統(tǒng)一管理的index.js:
import CountStore from "./count";
import MyInfo from "./info";
import React from "react";
class Store {
constructor() {
this.countStore = new CountStore()
this.myInfo = new MyInfo()
}
}
// 使用context是為了讓react識(shí)別到Store里面的mobx,不然react不認(rèn)識(shí)Store
const rootStore = new Store()
const context = React.createContext(rootStore)
export const useStore = () => React.useContext(context)
在組建中使用
像使用hooks一樣使用store,也可以使用解構(gòu)賦值的形式,將countStore解構(gòu)出來(lái):
import React from 'react'
import { useStore } from './store'
import { observer } from 'mobx-react-lite'
function App() {
const { countStore, myInfo } = useStore()
return (
<div>
<h2>APP組件</h2>
<div className="count-box">
count狀態(tài): {countStore.count}
<button onClick={countStore.addCount}>+</button>
</div>
<div>
myinfo狀態(tài): {myInfo.myCar.join('++')}
myAge狀態(tài): {myInfo.FilterAge.join('||')}
<button onClick={myInfo.addCar}>修改內(nèi)容</button>
</div>
</div>
)
}
export default observer(App)
使用效果
可以在React組建中調(diào)試查看數(shù)據(jù),找到對(duì)應(yīng)的組件,然后查看Hooks下Context屬性,找到里面有store的那個(gè),然后打開,即可查看里面存儲(chǔ)的數(shù)據(jù)
?文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-637957.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-637957.html
到了這里,關(guān)于React中使用mobx管理狀態(tài)數(shù)據(jù)使用樣例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!