一、介绍
Mobx是一个可以和React良好配合的几种状态管理工具
一、安装
npm i mobx mobx-react-lite
二、搭建结构
创建一个store目录,在store目录创建index.js入口文件,在分别创建store文件
1、创建子模块store文件
import { makeAutoObservable } from 'mobx'
// 初始化mobx
class CountStore{
// 定义数据
count:0,
countArr=[1,2,3,4,5],
// 数据响应式处理
constructor(){
makeAutoObservable(this)
}
// 定义一个计算属性 在方法前加get
get filterArr(){
return this.list.filter(item=>item>2)
}
// 定义action函数(修改数据)
addCount = ()=>{
this.count++
}
}
//导出实例
export default CountStore
2、 编写index.js组合模块样板代码
import React from 'react'
// 导入子模块
import ListStore from './listStore'
import CountStore from './countStore'
// 声明一个rootStore
class RootClass{
// 对子模块进行实例化
constructor(){
this.listStore = new ListStore()
this.counterStore = new CountStore()
}
}
// 实例化操作
const rootStore = new RootStore();
const context=React.createContext(rootStore);
const useStore=()=> React.useContext(context);
export default useStore
3、在组件中使用
import { observer } from 'mobx-react-lite'
import useStore from './store/index'
function App(){
const { counterStore } = useStore();
return(
<div className='app'>
{ counteStore.count }
</div>
)
}
// 使用observer包裹App将数据变成响应式数据
export default observer(App)