状态文件入口
// store.js
import a_state from './A_state'
import b_state from './B_state'
class Store {
constructor() {
this.A_state = new a_state()
this.B_state = new b_state()
}
}
export default new Store();
组件入口
// temp.js
import React, { Component } from 'react'
import A from './A'
import B from './B'
import Store from './store'
// Temp
export default class Temp extends Component {
aa = () => {
Store.A_state.change(10)
}
bb = () => {
Store.B_state.b_change("小红")
}
render() {
return (
<div>
<A />
<B />
<button onClick={this.aa}>改变年龄</button>
<button onClick={this.bb}>改变姓名</button>
</div>
)
}
}
A组件
// A.js
import React, { Component } from 'react'
import { autorun } from 'mobx'
import Store from './store'
export default class A extends Component {
state = {
a: 1
}
componentDidMount() {
autorun(() => {
console.log("获取到A的共享状态:", Store.A_state.a)
this.setState({
a: Store.A_state.total
})
})
}
render() {
return (
<div>
{this.state.a}
</div>
)
}
}
A状态
// A_state.js
import { observable, computed, action, makeObservable, configure } from 'mobx'
// 开启严格模式
configure({
enforceActions: 'always'
})
export default class a_state {
constructor() {
makeObservable(
//指定目标
this,
//定义当前mobx类对象中的数据类型
{
a: observable,
total: computed,
change: action,
}
)
}
a = 4
get total() {
return "他的年龄是:" + this.a
}
change(v) {
this.a = v
}
}
B组件
//B.js
import React, { Component } from 'react'
import { autorun } from 'mobx'
import Store from './store'
export default class B extends Component {
state = {
b: Store.B_state.b_total
}
componentDidMount() {
autorun(() => {
console.log("获取到B的共享状态:", Store.B_state.b_total)
this.setState({
b: Store.B_state.b_total
})
})
}
render() {
return (
<div>
{this.state.b}
</div>
)
}
}
B状态
// B_store.js
import { observable, computed, action, makeObservable, configure } from 'mobx'
// 开启严格模式
configure({
enforceActions: 'always'
})
export default class b_state {
constructor() {
makeObservable(
//指定目标
this,
//定义当前mobx类对象中的数据类型
{
b: observable,
b_total: computed,
b_change: action,
}
)
}
b = "小明"
get b_total() {
return "名字是:" + this.b
}
b_change(name) {
this.b = name
}
}