MobX。 @observable 有效但@computed 无效
MobX. @observable works but @computed don't
我有以下代码:
如果 _isFavorite
变量是 public observable
,它工作正常。但是一旦我将其更改为 @computed
,它只会触发一次。但进一步 @action
调用不会触发 @computed
.
这工作正常,一旦 isFarovite
改变:
class Cat {
@observable public isFavorite = false;
constructor() { ... }
@action public toggleFavorite() {
this.isFavorite = !this.isFavorite;
}
}
如果 _isFavorite
被更改,这将不起作用:
class Cat {
private _isFavorite = false;
constructor() { ... }
@computed public get isFavorite() {
return this._isFavorite;
}
@action public toggleFavorite() {
this._isFavorite = !this._isFavorite;
}
}
我想我可能会错过 "computed" 工作原理的核心概念,但我不知道应该如何更改我的代码...
这是因为 computed
值应该应用于某些 observables
。
它实际上检查其中使用了哪些observables
,并将自己注册为它的观察者并缓存结果。
class Cat {
@observable private _isFavorite = false;
constructor() { ... }
@computed public get isFavorite() {
return this._isFavorite;
}
@action public toggleFavorite() {
this._isFavorite = !this._isFavorite;
}
}
我有以下代码:
如果 _isFavorite
变量是 public observable
,它工作正常。但是一旦我将其更改为 @computed
,它只会触发一次。但进一步 @action
调用不会触发 @computed
.
这工作正常,一旦 isFarovite
改变:
class Cat {
@observable public isFavorite = false;
constructor() { ... }
@action public toggleFavorite() {
this.isFavorite = !this.isFavorite;
}
}
如果 _isFavorite
被更改,这将不起作用:
class Cat {
private _isFavorite = false;
constructor() { ... }
@computed public get isFavorite() {
return this._isFavorite;
}
@action public toggleFavorite() {
this._isFavorite = !this._isFavorite;
}
}
我想我可能会错过 "computed" 工作原理的核心概念,但我不知道应该如何更改我的代码...
这是因为 computed
值应该应用于某些 observables
。
它实际上检查其中使用了哪些observables
,并将自己注册为它的观察者并缓存结果。
class Cat {
@observable private _isFavorite = false;
constructor() { ... }
@computed public get isFavorite() {
return this._isFavorite;
}
@action public toggleFavorite() {
this._isFavorite = !this._isFavorite;
}
}