我正在尝试创建一个定时缓冲区,该缓冲区仅在可观察的mobx中存储1个项目。我在商店中调用一个创建计时器的函数,以便在计时器完成之前不能在商店中保存其他任何项目。但是,即使有可能,可观察的方法似乎也将其覆盖。
我正在尝试2件事(定时缓冲区数组大小限制器)
可观察对象是否覆盖标准的javascript数组方法/函数?
在React中可观察到的输出上,我看到了一个巨大的数组,并且不限于长度为1。
addTourList(node);
这是我的store.js mobx类。
import { action, autorun, observable, computed, toJS } from 'mobx';
import { onError } from 'mobx-react';
class MainStore {
@observable
tourList = [];
tourBuffer = null;
addTourList(node) {
if(node.loc == undefined){
return false;
}else{
if(this.tourBuffer == null){
this.buffer = function(){
console.log('END TOUR BUFFER TIMER!');
this.tourBuffer = null;
}
this.updateTourList(node)
console.log('START TOUR BUFFER TIMER!');
this.tourBuffer = setTimeout( this.buffer.bind(this), 4000);
}else{
console.log("TOUR ANIMATION BUSY");
}
return true;
}
}
@action
updateTourList(node) {
var maxStoreData = 1;
this.tourList.unshift(node);
this.tourList.slice(0, maxStoreData);
}
}
const store = (window.store = new MainStore());
onError(error => {
console.log('STORE ERROR:', error);
});
export default store;
可观察对象是否覆盖标准的javascript数组方法/函数?
他们没有,他们只是将功能扩展到可以使用可观察值的地步。您可能还会遇到一些陷阱,尤其是在使用Mobx 4.x(docs)的情况下。
在React中可观察到的输出上,我看到了一个巨大的数组,并且不限于长度为1
如果看到它,您必须使用Mobx4.x。实际上,这是正常现象,如果您检查数组长度,它将被设置为数组中元素的实际数量,因此无需担心。或者只是更新到使用Proxy
界面的Mobx 5.x版本,这样您就可以直接看到阵列。
作为示例,您可以随时通过调用tourList
函数来阻止对blockTourListMutationFor
变量的任何突变,以将要防止此变量的任何突变的时间设置为几毫秒。
import { observable, action } from "mobx";
class MyStore {
@observable tourList = [];
isAllowedToMutateTourList = true;
tourListTimeout;
@action setTourList = val => {
if (!this.isAllowedToMutateTourList) return;
this.tourList = val;
};
blockTourListMutationFor = (timeout) => {
this.isAllowedToMutateTourList = false;
this.tourListTimeout = setTimeout(
action(() => {
this.isAllowedToMutateTourList = true;
}),
timeout
);
};
}
const store = new MyStore();
// will update tourList
store.setTourList([1]);
console.log(store);
store.blockTourListMutationFor(500);
// will not update tourList, bacause it's blocked for 500 ms
store.setTourList([1, 2]);
console.log(store);
setTimeout(() => {
// will update tourList, because 500ms will pass by that time it executes
store.setTourList([1, 2, 3]);
console.log(store);
}, 1000);
我希望您觉得这个答案有用:)