`console.log`一个mobx` @ observable`只要它的值发生变化

时间:2017-02-02 13:18:03

标签: javascript state observable mobx

当mobx console.log更改值时,@observable是否会自动触发?

我会使用mobx dev工具进行操作,但它会触发大量的控制台日志,因此很难确定我正在跟踪其值的属性。

2 个答案:

答案 0 :(得分:3)

哟可以这样做:

//store.js
import { autorun } from 'mobx';
autorun(() => {
  console.log(store.value); //value is an observable.
});

答案 1 :(得分:3)

您也可以使用Reaction, 对于记录你可能想要使用自动运行,但你应该知道另外一个选项, 可以让您更好地控制何时运行回调。

我也喜欢它,因为语法更有意义:

import { reaction } from 'mobx'

class SomeStore {
    @observable item;
    @observable otherObservable;

    constructor() {
        reaction(
            // The callback will run only on change 
            // of observables described in this function
            () => this.item,
            // You can use whatever observables/computed values in this function
            // without making the function run on an unwanted observables change
            () => {
                if (this.otherObservable) {
                    doSometing();
                }
            }
        )
    }
}

此功能有更多选项,您可以在提供的链接中阅读。