我正在探索MobX并对一个问题感兴趣:
如果我有这个可观察的:
class ItemsStore {
@observable items = [1,2,3];
}
const store = new ItemsStore;
Run Code Online (Sandbox Code Playgroud)
然后像这样改变它:
setInterval(() => {
store.items[0] = +new Date
}, 1000)
Run Code Online (Sandbox Code Playgroud)
我注意到以下几点:
autorun(() => console.log(store.items)); 从不开火......autorun(() => console.log(store.items[0])); 每1秒触发一次,并给出一个新值autorun(() => console.log(store.items.length)); 虽然价值不变,但每1秒触发一次这背后的API逻辑是什么?我希望store.items永远不会激发,不变的属性会表现得相同.
为什么MobX知道我的回调中有什么代码?它是否正在分析我传递给我的回调autorun?
console.log(商店.项目)
当上次自动运行中取消引用的可观察量发生更改时,会触发自动运行。store.items不取消引用任何可观察量。尝试store.items.slice()或store.items.toJS()获得想要的效果。
console.log(商店.items[0])
这是因为取消引用的可观察对象发生了更改而被触发。
console.log(store.items.length)
这是因为 MobX 数组不是真正的数组而运行。该length属性定义如下:
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function(): number {
return this.$mobx.getArrayLength();
},
set: function(newLength: number) {
this.$mobx.setArrayLength(newLength);
}
});
Run Code Online (Sandbox Code Playgroud)
getArrayLength 报告已观察到 MobX 数组:
getArrayLength(): number {
this.atom.reportObserved();
return this.values.length;
}
Run Code Online (Sandbox Code Playgroud)