[英]@observable on numeric type doesn't create observable
When trying to use @observable on a numeric type it doesn't create an Observable. 尝试在数字类型上使用@observable时,不会创建Observable。 This causes the problem where the computed value gets recalculated every time it is fetched. 这会导致出现问题,即每次获取计算值时都要重新计算。 I don't want the computed value to get recalculated unless the inputs have changed, what is the problem here? 我不希望重新计算计算值,除非输入已更改,这是什么问题?
https://jsbin.com/mofirujixu/1/edit?html,js,console https://jsbin.com/mofirujixu/1/edit?html,js,console
class Square {
@observable width = 2;
@computed get area() {
console.log('calc area');
return this.width * this.width;
}
}
const square = new Square();
//prints out 'calc area' each time
console.log(square.area);
console.log(square.area);
console.log(square.area);
MobX only caches the resulting value of a computed if it is being observed by one or more observers. MobX仅在一个或多个观察者观察某个计算结果时才对其进行缓存。 It is implemented this way to decrease memory footprint and to allow the garbage collector to do its job. 它以这种方式实现,以减少内存占用并允许垃圾收集器完成其工作。
You could use a simple autorun
before the logs to see this in action: 您可以在日志之前使用简单的autorun
来查看实际效果:
class Square {
@observable width = 2;
@computed get area() {
console.log('calc area');
return this.width * this.width;
}
}
const square = new Square();
autorun(() => {
square.area;
// square.area is now observed by one observer,
// and will not be re-calculated for subsequent reads.
});
console.log(square.area);
console.log(square.area);
console.log(square.area);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.