autorun响应式函数,常用与打印日志、持久化或者更新UI的代码
var numbers = observable([1,2,3]);var disposer = autorun(() => console.log(sum.get())); // 输出 '6' numbers.push(4); // 输出 '10' disposer(); numbers.push(5); // 不会再输出任何值。
observe可监听新旧值newValue、oldValue
import {observable, observe} from 'mobx'; const person = observable({ firstName: "Maarten", lastName: "Luther" }); const disposer = observe(person, (change) => { console.log(change.type, change.name, "from", change.oldValue, "to", change.object[change.name]); }); person.firstName = "Martin"; // 输出: 'update firstName from Maarten to Martin' disposer(); // 忽略任何未来的变化 // 观察单个字段 const disposer2 = observe(person, "lastName", (change) => { console.log("LastName changed to ", change.newValue); });
本文地址: