【问题标题】:`console.log` a mobx `@observable` whenever its value changes`console.log` 一个 mobx `@observable` 每当它的值改变时
【发布时间】:2020-10-05 23:56:03
【问题描述】:

有没有什么方法可以让 console.log 在 mobx @observable 更改值时自动触发?

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

【问题讨论】:

    标签: javascript state observable mobx


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      您也可以使用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();
                      }
                  }
              )
          }
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多