pnpm i mobx mobx-react-lite
or
npm i mobx mobx-react-lite
or
yarn add mobx mobx-react-lite
Store
状态管理层import { makeAutoObservable } from 'mobx'
class StateStore {
// 响应式
constructor(){
makeAutoObservable(this)
}
// 状态
stateA=[1,2,3]
// 计算属性
get computedA = () =>{
...code
}
// 修改状态方法
setStateA = () =>{
this.stateA = []
}
}
// 导出示例
export const stateA= new StateStore()
Store
层./store/index.store.js
import {createContext, useContext} from 'react'
import {stateA} from './stateA.store'
import {stateB} from './stateA.store'
class IndexStore {
constructore(){
this.stateA = stateA
this.stateB = stateB
}
}
export const indexStore = useContext(createContext(IndexStore))
observer
订阅indexStore
的内容将mobx
与react
进行连接App.jsx
import {observer } from 'mobx-react-lite'
import {indexStore } from './store/index.store'
function App(){
const store = indexStore()
const storeA = index.store().stateA
const storeAFun = index.store().stateA.setStateA
}
export default observer(App)