npm i mobx npm i mobx-react-lite
新建store/lists.Store.js
import { makeAutoObservable } from "mobx"
class ListStore{
list = ['react','vue'] //定义变量
constructor(){ //响应式处理
makeAutoObservable(this)
}
addList=()=>{ //方法
this.list.push('angular')
}
//计算属性
get filterList(){
return this.list.filter(item=>item==='vue')
}
}
export {ListStore}
新建store/index.js
//组合子模块
//封装统一导出业务
import React from 'react'
import { ListStore } from './lists.Store'
import { CounterStore } from './counter.Store'
class RoutStore {
constructor() {
this.listStore = new ListStore() //子模块
}
}
const rootStore = new RoutStore()
//react context机制完成方法统一
const context = React.createContext(rootStore)
const useStore = ()=>React.useContext(context)
export { useStore }
组件使用
import { useStore } from "./store";
function App() {
const {counterStore,listStore} = useStore()
return (
<div>
{listStore.list.join(',')}
<button onClick={listStore.addList}>addList</button>
计算属性
{listStore.filterList.join(',')}
</div>
);
}
export default observer(App);