当尝试在数字类型上使用@observable时,它不会创建Observable。这会导致每次获取计算值时重新计算的问题。除非输入已经改变,否则我不希望重新计算计算值,这里有什么问题?
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);
答案 0 :(得分:0)
如果一个或多个观察者正在观察计算的结果值,则MobX仅缓存计算结果的值。它以这种方式实现,以减少内存占用并允许垃圾收集器完成其工作。
您可以在日志之前使用简单的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);