我正在探索 MobX 并对一个问题感兴趣:
如果我有这个可观察的:
class ItemsStore {
@observable items = [1,2,3];
}
const store = new ItemsStore;
然后像这样改变它:
setInterval(() => {
store.items[0] = +new Date
}, 1000)
我注意到以下几点:
-
autorun(() => console.log(store.items));
从来不火... https://jsfiddle.net/f2yx2ouw/1/
-
autorun(() => console.log(store.items[0]));
每 1 秒触发一次并给出一个新值 https://jsfiddle.net/f2yx2ouw/2/
-
autorun(() => console.log(store.items.length));
尽管值不变,但每 1 秒触发一次 https://jsfiddle.net/f2yx2ouw/3/
这背后的API逻辑是什么?我希望从那时起store.items
从不点火,那属性不变会表现得一样。
MobX 怎么知道我的回调里面有什么代码?它正在分析我传递给的回调吗autorun
?
console.log(商店.项目)
当上次自动运行中取消引用的可观察量发生更改时,会触发自动运行。store.items
不取消引用任何可观察量。尝试store.items.slice()
or store.items.toJS()
以获得想要的效果。
console.log(商店.items[0])
这是因为取消引用的可观察对象发生了更改而被触发。
console.log(store.items.length)
这是因为 MobX 数组不是真正的数组而运行。这length
财产是定义如下 https://github.com/mobxjs/mobx/blob/master/src/types/observablearray.ts#L428:
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function(): number {
return this.$mobx.getArrayLength();
},
set: function(newLength: number) {
this.$mobx.setArrayLength(newLength);
}
});
getArrayLength
报告已观察到 MobX 数组 https://github.com/mobxjs/mobx/blob/master/src/types/observablearray.ts#L116:
getArrayLength(): number {
this.atom.reportObserved();
return this.values.length;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)