MobX 自动运行只触发一次
MobX autorun firing just once
我正在学习 MobX,不明白为什么 autorun
只触发一次...
const {observable, autorun} = mobx;
class FilterStore {
@observable filters = {};
@observable items = [1,2,3];
}
const store = window.store = new FilterStore;
setInterval(() => {
store.items[0] = +new Date
}, 1000)
autorun(() => {
console.log(store.filters);
console.log(store.items);
console.log('----------------');
});
jsFiddle: https://jsfiddle.net/1vmtzn27/
这是一个非常简单的设置,setInterval
每秒都在更改我的可观察数组的值,但是 autorun
没有被触发...知道为什么吗?
...and the setInterval
is changing the value of my observable array every second...
不,不是。它改变了数组的 contents,但不是观察到的 MobX 正在观察,它是 store.items
本身。更改 that 将如下所示:
store.items = [+new Date];
由于您没有在 autorun
回调中访问 store.items[0]
,因此不会监视更改。 (console.log
确实访问了它,但不是以 MobX 可以看到的方式。)
如果您做访问store.items[0]
,它会被监视变化;如果您添加到数组或从数组中删除,您可能还想显式访问 length
:
autorun(() => {
store.filters;
store.items.length;
store.items.forEach(function() { } );
console.log('Update received');
});
我正在学习 MobX,不明白为什么 autorun
只触发一次...
const {observable, autorun} = mobx;
class FilterStore {
@observable filters = {};
@observable items = [1,2,3];
}
const store = window.store = new FilterStore;
setInterval(() => {
store.items[0] = +new Date
}, 1000)
autorun(() => {
console.log(store.filters);
console.log(store.items);
console.log('----------------');
});
jsFiddle: https://jsfiddle.net/1vmtzn27/
这是一个非常简单的设置,setInterval
每秒都在更改我的可观察数组的值,但是 autorun
没有被触发...知道为什么吗?
...and the
setInterval
is changing the value of my observable array every second...
不,不是。它改变了数组的 contents,但不是观察到的 MobX 正在观察,它是 store.items
本身。更改 that 将如下所示:
store.items = [+new Date];
由于您没有在 autorun
回调中访问 store.items[0]
,因此不会监视更改。 (console.log
确实访问了它,但不是以 MobX 可以看到的方式。)
如果您做访问store.items[0]
,它会被监视变化;如果您添加到数组或从数组中删除,您可能还想显式访问 length
:
autorun(() => {
store.filters;
store.items.length;
store.items.forEach(function() { } );
console.log('Update received');
});