【问题标题】:Observable private property in MobxMobx 中可观察的私有财产
【发布时间】:2020-07-14 15:23:59
【问题描述】:

我对 Mobx 商店中的可观察私有财产有疑问。问题是带有 getter 和 setter 的可观察私有属性不起作用,而公共可观察属性则完全正常。为什么会这样?我交替测试了私有和公共财产(#privateSelectedTypeselectedType)来做同样的事情。

EDIT2:我创建了一个代码框来更好地展示案例:https://codesandbox.io/s/tender-pond-kglzr?file=/src/carsStore.js

这是一个示例情况的代码。我用这个商店显示所有类型并标记selectedType

class CarsStore {
  #types = ["defaultType", "type1", "type2"];
  #privateSelectedType = "defaultType";
  selectedType = "defaultType";

  otherThings = [];

  get types() {
    return this.#types;
  }

  get privateSelectedType() {
    return this.#privateSelectedType;
  }

  set privateSelectedType(selectedType) {
    this.#privateSelectedType = selectedType;
    // call function updating otherThings, that's why I want to use setter in this store
    this.#updateOtherThings();
  }

  #updateOtherThings = () => {
    //update otherThings
  }
}

decorate(CarsStore, {
  "#types": observable,
  "#privateSelectedType": observable,
  selectedType: observable,
  otherThings: observable
});

编辑:只需将所有出现的#privateSelectedType 更改为公共字段_publicSelectedType 即可使此代码正常工作。在我看来,mobx 对 JavaScript 私有字段根本不起作用或工作方式不同。

【问题讨论】:

    标签: observable private mobx


    【解决方案1】:

    编辑答案:

    在对您在 cmets 中的代码进行一些研究和调试后,发现 mobx 内部正在尝试装饰 CarsStore 的原型属性,其中私有字段缺少

    原因是在这个提议语法中,私有字段只能从类的主体中看到和访问,因为它们被记录为元数据并且只能从引擎访问。此link(point 5) 中的更多信息。我希望这现在可以回答您的问题。

    【讨论】:

    • 不幸的是,它在我的情况下不起作用。当我使用 getter 和 setter 转到私有字段时,无论是否计算,它都会停止工作。
    • 你能写下确切的代码不工作吗?
    • 我已经创建了代码的沙箱示例。在carsStore 文件中,如果您将所有出现的#selectedTypeName 更改为公共内容,它就会开始工作。 codesandbox.io/s/tender-pond-kglzr?file=/src/carsStore.js
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多