官网地址:https://mobx.js.org/README.html
Simple, scalable state management 简单,可扩展的状态管理器
安装
npm install -s mobx mobx-react
创建监视数据
用法:
- observable(value)
- @observable classProperty = value
Observable 值可以是JS基本数据类型、引用类型、普通对象、类实例、数组和映射。 匹配类型应用了以下转换规则,但可以通过使用调节器进行微调。
const map = observable.map({ key: "value" })
map.set("key", "new value")
const list = observable([1, 2, 4])
list[2] = 3
const person = observable({
firstName: "Clive Staples",
lastName: "Lewis"
})
person.firstName = "C.S."
const temperature = observable.box(20)
temperature.set(25)
改变数据 observables
用法:
- action(fn) action(name, fn)
- @action classMethod() {}
- @action(name)
classMethod () {} - @action boundClassMethod = (args) => { body }
- @action(name) boundClassMethod = (args) => { body }
- @action.bound
classMethod() {}
任何应用都有动作。动作是任何用来修改状态的东西。
案例
import React from "react";
import { observer } from "mobx-react";
import { action, observable, autorun, when} from "mobx";
// create observer
const appState = observable({ timer: 0 });
// create action
const addTimer = action(() => {
setTimeout(()=>{ appState.timer += 1}, 1000)
})
const resetTimer = action(() => {
appState.timer = 0;
})
const App = observer((appState) => {
return (
<div className="App">
timer值:{appState.timer }
<button onClick={addTimer}>add+1 </button>
<button onClick={resetTimer}>resetTimer </button>
</div>
);
});
export default App
类案例,
class Ticker {
@observable tick = 0
@action.bound
increment() {
this.tick++ // 'this' 永远都是正确的
}
}
const ticker = new Ticker()
setInterval(ticker.increment, 1000)
监听改变及响应
- computed 计算值
- autorun 响应式函数
- when 自定义响应
- reaction 更颗粒度的autorun
1.computed 计算值
class MobxClass extends React.Component{
@observable price = 10;
@observable amount = 6.8;
@computed get total() {
return this.price * this.amount;
}
render(){
return (
<div>
<p>price: {this.price}</p>
<p>amount: {this.amount}</p>
<p>price*amount:{this.total}</p>
</div>
)
}
}
export default MobxClass
2. autorun 响应式函数
选项
Autorun 接收第二个参数,它是一个参数对象,有如下可选的参数:
- delay: 可用于对效果函数进行去抖动的数字(以毫秒为单位)。如果是 0(默认值) 的话,那么不会进行去抖。
- name: 字符串,用于在例如像 spy 这样事件中用作此 reaction 的名称。
- onError: 用来处理 reaction 的错误,而不是传播它们。
- scheduler: 设置自定义调度器以决定如何调度 autorun 函数的重新运行
autorun(() => {
console.log('autorun')
}, {
name: 'john',
delay: 300,
onError(e) {
window.alert("Please enter a valid age")
},
});
3.when 自定义反应
class MyResource {
constructor() {
when(
// 一旦...
() => !this.isVisible,
// ... 然后
() => this.dispose()
);
}
@computed get isVisible() {
// 标识此项是否可见
}
dispose() {
// 清理
}
}
4.Reaction
autorun 的变种,对于如何追踪 observable 赋予了更细粒度的控制。
用法: reaction(() => data, (data, reaction) => { sideEffect }, options?)。
选项
Reaction 接收第三个参数,它是一个参数对象,有如下可选的参数:
粗略地讲,reaction 是 computed(expression).observe(action(sideEffect)) 或 autorun(() => action(sideEffect)(expression)) 的语法糖。
const counter = observable({ count: 0 });
// 只调用一次并清理掉 reaction : 对 observable 值作出反应。
const reaction3 = reaction(
() => counter.count,
(count, reaction) => {
console.log("reaction 3: invoked. counter.count = " + count);
reaction.dispose();
}
);
counter.count = 1;
// 输出:
// reaction 3: invoked. counter.count = 1
counter.count = 2;
// 输出:
// (There are no logging, because of reaction disposed. But, counter continue reaction)
console.log(counter.count);
// 输出:
// 2