observable - Mobx 中可观察的私有财产
问题描述
我对 Mobx 商店中的可观察私有财产有疑问。问题是带有 getter 和 setter 的可观察私有属性不起作用,而公共可观察属性则完全正常。为什么会这样?我交替测试了私有和公共财产(#privateSelectedType
和selectedType
)来做同样的事情。
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 私有字段根本不起作用或工作方式不同。
解决方案
编辑答案:
在对评论中的代码进行了一些研究和调试之后,发现 mobx 内部正在尝试装饰 CarsStore 的原型属性,其中缺少私有字段:
这样做的原因是,在这个提案语法中,私有字段只能从类的主体中可见和可访问,因为它们被记录为元数据并且只能从引擎访问。此链接中的更多信息(第 5 点) 。我希望这现在能回答你的问题。
推荐阅读
- angular - 尝试重新分配属性时未定义
- javascript - 页面刷新后如何保存多个 IMG?
- php - 如何在 WordPress 中显示移动菜单?
- c++ - 无法使用 google Mock 模拟 CDatabase Open 函数
- python - 从 Python 使用 Elasticsearch API 时删除的文档
- java - 如何纠正java项目中的所有有效库?
- python - Pandas:将 2D 数据帧转换为 3D 数据帧
- android - Firebase 订阅的主题在重新安装应用程序后不起作用
- python - python dataframe 列中每个条目的最新 x 行
- struts2 - 如何在 Struts 2 中创建语言选择器?