当前位置: 首页 > 工具软件 > Mobx-React > 使用案例 >

使用mobx与mobx-react-lite与React连接进行状态管理

夏知
2023-12-01

导入

  1. 下载
pnpm i mobx mobx-react-lite
or
npm i mobx mobx-react-lite
or
yarn add mobx mobx-react-lite

使用

  1. 定义Store状态管理层
    ./store/stateA.store.js
import { makeAutoObservable } from 'mobx'

class StateStore {
	// 响应式
	constructor(){
		makeAutoObservable(this)
	}
// 状态
	stateA=[1,2,3]
	
// 计算属性
get computedA = () =>{
	...code
}

// 修改状态方法
setStateA = () =>{
	this.stateA = []
}

}
// 导出示例
export const stateA= new StateStore()
  1. 集中管理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))

  1. 使用, 通过observer订阅indexStore的内容将mobxreact进行连接

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)
 类似资料: