mobx 应用和源码
mobx 应用和源码
状态流转
- 页面事件(生命周期、点击事件等等)触发 action 的执行。
- 通过 action 来修改状态。
- 状态更新后,
computed计算属性也会根据依赖的状态重新计算属性值。 - 状态更新后会触发
reaction,从而响应这次状态变化来进行一些操作(渲染组件、打印日志等等)。
特点
- 响应式编程(Reactive Programming)。和vue类似。
- 可以作为状态库单独使用,和redux类似,也可配合 react 使用。
- 可以定义多个store,和Redux不同。
- 在React Class Component模式下,使用装饰器;在React Hooks模式下,使用相关Hooks。
源码实现
我的实现:
mbox+react使用
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
// 声明多个store
// 每个store就利用 @action @observable 来定义行为以及状态
import UserStore from './User/store';
import StatisticalCenterStore from './StatisticalCenter/store';
import AccountSettingStore from './AccountSetting/store';
import CallRecordStore from './CallRecord/store';
class RootStore {
constructor() {
this.userStore = new UserStore();
this.statisticalCenterStore = new StatisticalCenterStore();
this.accountSettingStore = new AccountSettingStore();
this.callRecordStore = new CallRecordStore();
}
}
export default new RootStore();
// 注入 store
ReactDOM.render(
<Provider rootStore={RootStore}>
...
</Provider>,
document.getElementById('root')
);
// 使用store
import { observer, inject } from 'mobx-react';
@inject('rootStore') // 借助 @inject 将 state 挂入到 React Component 上,作用类似 redux 的 connect 函数
@observer
class Index extends Component {
constructor(props) {
super(props);
}
render() {
const userStore = this.props.rootStore.userStore; // 访问具体store
return (
<>
</>
);
}
}
export default Index;
单独使用mobx(API用法)
本文由作者按照 CC BY 4.0 进行授权
