Mobx 常用函数整理

 

在实际开发中,需要用到不少 mobx 的辅助函数,这些辅助函数一共 14 个,挑了一些列举如下。
 
autorun
observable 的值初始化或改变时,自动运行。
 
const age = observable(10)
const dispose = autorun(() => {
    if (age.get() < 0)
        throw new Error("Age should not be negative")
    console.log("Age", age.get())
})


age.set(18)  // 输出: Age 18
age.set(-10) // 输出: Age should not be negative
age.set(5)   // 已恢复; 输出: Age 5

dispose.onError(e => {
    window.alert("Please enter a valid age")
})

age.set(-5)  // 显示alert弹出框

 

 

trasaction
批量改变时,通过 trasaction 包装,只会触发一次 autorun。
 
import {observable, transaction, autorun} from "mobx";

const numbers = observable([]);

autorun(() => console.log(numbers.length, "numbers!"));
// 输出: '0 numbers!'

transaction(() => {
    transaction(() => {
        numbers.push(1);
        numbers.push(2);
    });
    numbers.push(3);
});
// 输出: '3 numbers!'

 

 
extendsObservable
对类的属性或实例,进行监听。
与 Object.assign 十分类似,extendObservable 接收两个或者更多的参数,一个是 target 对象,一个或多个 properties 映射。 它会把 properties 映射中的所有键值对添加到 target 对象中作为 observable 属性
var matthew = new Person("Matthew", "Henry");

// 为已存在的 observable 对象添加一个 observable 属性
extendObservable(matthew, {
    age: 353
});

 

observable
对普通对象进行监听。
observable(value)
@observable classProperty = value

 

map
使用 asMap 将对象转化为 map。
 
action-strict
在 mobx.usrStrict(true)时,只能通过 action 触发值的改变。
 
when
类似 autorun.
 
mobx.when 第一个参数是一个函数,初始化时也会自动执行。该函数返回一个 boolean 值,当返回值为 true 的时候,才会继续触发第一个函数。当返回值为 flase 时,不再继续监听。这时会执行 mobx.when 的第二个参数,这个参数也是一个函数。
 
reaction
类似 autorun.
reaction 不会在初始化时执行,只会在值改变的时候执行。
该函数有 2 个值,第一个参数是一个函数,返回监听的值.第二个参数,也是一个函数,会在值改变的时候执行。
 
const todos = observable([
    {
        title: "Make coffee",
        done: true,
    },
    {
        title: "Find biscuit",
        done: false
    }
]);

// reaction 的错误用法: 对 length 的变化作出反应, 而不是 title 的变化!
const reaction1 = reaction(
    () => todos.length,
    length => console.log("reaction 1:", todos.map(todo => todo.title).join(", "))
);

// reaction 的正确用法: 对 length 和 title 的变化作出反应
const reaction2 = reaction(
    () => todos.map(todo => todo.title),
    titles => console.log("reaction 2:", titles.join(", "))
);

 

spy
类似 aoturun.
监听所有 mobx 的事件。
包含一个 type ,该值用来区分执行事件的类型。
 
spy((event) => {
    if (event.type === 'action') {
        console.log(`${event.name} with args: ${event.arguments}`)
    }
})

 

 
whyRun
用于调试,打印 autorun 为什么会触发。
 
 
 
posted @ 2017-07-27 10:45  Yaphet_peng  阅读(1300)  评论(0编辑  收藏  举报