了解下 MobX 概念
7月 19, 2021
注意:此文章已超过 1 年未更新,部分信息可能已经过时。
基本概念#
- observable 函数
- 定义状态值
- action 函数
- 用于修改状态值
- 接受一个函数,返回一个签名相同的函数,提供触发时调用。
- derivations 派生,有两种:
autorun和computed- reactions - autorun()
- 接受一个函数
- 状态值发生改变后要执行的响应操作。
- computed value - computed()
- 接受一个函数,返回计算值对象。
- 状态值发生改变时,计算值对象的值会自动更新。
- reactions - autorun()
observable#
MobX 中通过 observable 来定义可观察状态。
import { observable, autorun, computed, action } from "mobx";
// 定义状态
const store = observable({
count: 0
});derivations#
autorun#
MobX 中通过 autorun 来定义状态变化时要执行的响应操作,它接受一个函数,每当 observable 定义的状态发生变化时,MobX 都会立即执行该函数。
import { observable, autorun, computed, action } from "mobx"
autorun(() => {
console.log("count:", store.count);
});直接修改 store 或通过 action 都可以触发 autorun:
const store = observable({
a: 1
});
const increaseA = action(() => {
store.a += 1;
});
store.a += 1
// 或者
increaseA();computed#
状态值发生改变时,计算值对象的值会自动更新。
import { observable, autorun, computed, action } from "mobx"
const doubleCount = computed(() => 2 * store.count);action#
不管 action 里面对 store 的修改次数有几次,一次 action 的调用最终只会触发一次 autorun 的执行。
const increaseA = action(() => {
store.a += 1;
store.a += 1;
});
increaseA();和 react 结合#
使用 mobx-react 包:
import React from "react";
import { observable } from "mobx";
import { observer } from "mobx-react";
class Counter extends React.Component {
constructor(props) {
super(props);
this.store = observable({
count: 0
});
}
render() {
return (
<button onClick={() => this.store.count++}>
{this.store.count}
</button>
)
}
}
export default observer(Counter);