1.定义独立的countes模块和list模块
2.在index.js导入 拆分的模块
3.使用React的 useContext机制导出统一的useStore方法
代码示例:
//countesStore.js
import { makeAutoObservable } from 'mobx'
class CountesStore {
// 1.定义数据
count = 0
// 2.数据响应式处理
constructor() {
makeAutoObservable(this)
}
// 3.定义一个函数
addcount = () => {
this.count++
}
}
export { CountesStore }
listStore.js
import { computed, makeAutoObservable } from 'mobx'
class ListStore {
// 1.定义数据
list = [1, 2, 3, 4, 5, 6]
// 2.数据响应式处理
constructor() {
makeAutoObservable(this, {
filterList: computed
})
}
// 计算属性
get filterList () {
return this.list.filter(item => item > 3)
}
// 3.定义一个函数
addList = () => {
this.list.push(0, 7, 8)
}
}
export { ListStore }
index.js
import React from 'react'
import { CountesStore } from './countesStore'
import { ListStore } from './listStore'
class RootStore {
constructor() {
this.countesStore = new CountesStore()
this.listStore = new ListStore()
}
}
// 实例化store
const rootStore = new RootStore()
const context = React.createContext(rootStore)
// 导出useStore
const useStore = () => React.useContext(context)
export { useStore }
App.js
// 1.countesStore
import { useStore } from './store/index'
// 2.导入中间连接件,使数据完成响应式
import { observer } from 'mobx-react-lite'
function App () {
// 解构赋值,需要哪个就使用哪个,防止破坏响应式
const { countesStore } = useStore()
return (
<div className="App">
{/* 渲染数据 */}
{countesStore.count}
{/* 对数据进行修改 */}
<button onClick={countesStore.addcount}>++</button>
</div>
)
}
// 包裹App组件
export default observer(App)