React项目中使用Mobx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// /store/appState.ts
import { observable, action } from 'mobx';

// MobX 中启用了strict-mode,严格模式下,修改可观察状态(observable)的值时必须使用 action。
// 这是为了确保状态的修改是可追踪的、可预测的,从而避免不必要的副作用和错误
export interface IAppState {
count: number;
increment: () => void;
decrement: () => void;
setCount: (value: number) => void;
}
export const appState:IAppState = observable({
count: 0,
increment: action(function (this: IAppState) {
this.count++;
}),
decrement: action(function (this: IAppState) {
this.count--;
}),
setCount: action(function (this: IAppState, value: number) {
this.count = value;
}),
});


/**
* ❌❌❌
// increment() {
// this.count++;
// },
// decrement() {
// this.count--;
// },
*/

1
2
3
4
// 修改
appState.increment()
appState.setCount(10)
// ...
1
2
3
4
5
import { observer } from 'mobx-react';

const Count: React.FC = observer(()=>{
return (<Fragment>{appState.count}</Fragment>)
})

数据持久化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { action  } from "mobx"
import { makeAutoObservable } from "mobx"
import { makePersistable } from "mobx-persist-store"; // 引入相关api



class AppState {
user_info: {
avatar: string,
gender: number,
nickname: string,
phone: string,
} | undefined = undefined;
constructor() {
makeAutoObservable(this, {}, { autoBind: true })
makePersistable(this, {
name:'mainStore',
properties: [
"user_info"
],
storage: window.localStorage,
expireIn: 86400000,
removeOnExpiration: true,
debugMode: false,
})
.then(
action((persistStore: {
rehydrated: boolean;
rehydrate: () => void;
}) => {
// persist 完成的回调,在这里可以执行一些拿到数据后需要执行的操作,如果在页面上要判断是否完成persist,使用 isHydrated
console.log('mainStore持久化加载完成',persistStore);
}
))
}
setUserInfo(userInfo: { avatar: string; gender: number; nickname: string; phone: string; } | undefined) {
this.user_info = userInfo;
}

}

export const appState = new AppState()