【问题标题】:How to make class objects observable in MobX?如何使类对象在 MobX 中可观察?
【发布时间】:2019-12-27 12:04:16
【问题描述】:

我有一个班级:

class Field{

  constructor(name) {
    this.name= name
    this.otherAttr = null
  }

  changeName(newName) {
    this.name = newName
  }
}


const f = new Field("Charanjit")
f.setName("Singh") // It shoukd reflect in observer 

f.name = "Rahul" // It should also reflect in observer


如何使f 对象可观察,以便f 属性的任何更改都会更新观察者组件。

目前,我收到错误:https://github.com/mobxjs/mobx/issues/1932 如果我使用:

@observable(f)
>>> It shows Error: https://github.com/mobxjs/mobx/issues/1932

【问题讨论】:

    标签: reactjs mobx mobx-react mobx-state-tree


    【解决方案1】:

    查看 MobX 文档,这样做可能是一个好方法:

    import { observable, action, decorate } from "mobx";
    
    class Field {
        name = '';
        otherAttr = null;
    
        changeName(name) {
            this.name = name;
        }
    }
    
    decorate(Field, {
        name: observable,
        otherAttr: observable,
        changeName: action
    })
    

    使用 decorate 实用程序将属性标记为可观察对象将满足您的需求。 请浏览文档:https://mobx.js.org/best/decorators.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2016-10-30
      • 2023-01-10
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多