reactjs - 限制 mobx 存储以仅在数组中保存 1 项
问题描述
我正在尝试创建一个定时缓冲区,它只在 mobx observable 中存储 1 个项目。我在 store 中调用了一个函数,该函数创建了一个计时器,这样在计时器完成之前,无法将其他项目保存在 store 中。然而,如果可能的话,可观察的似乎是压倒一切的。
我正在尝试两件事(定时缓冲区,数组大小限制器)
observables 会覆盖标准的 javascript 数组方法/函数吗?
在 React 中 observable 的输出中,我看到了一个巨大的数组,并且不限于长度为 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;
解决方案
observables 会覆盖标准的 javascript 数组方法/函数吗?
他们没有,他们只是将功能扩展到您可以使用可观察值的地步。您可能还会遇到一些问题,尤其是在您使用 Mobx 4.x( docs ) 时。
在 React 中 observable 的输出中,我看到了一个巨大的数组,并且不限于长度为 1
如果看到它,您必须使用 Mobx 4.x。这是正常行为,实际上,如果您检查数组长度,它将被设置为数组中元素的实数,因此无需担心。或者只是更新到使用接口的 Mobx 5.x 版本Proxy
,所以你会看到你的数组。
例如,您可以随时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);
我希望你觉得这个答案有用:)
推荐阅读
- android - 如何在不覆盖现有应用程序的情况下运行 Flutter 项目的副本?
- sql - 如何创建循环依赖成员凭证
- mysql - 从多个表中选择,即使一个表没有任何对应的记录
- mongodb - MongoDB 中的子查询,用于返回具有特定字段的单个元素
- mysql - 计算年份 beetwen 两个日期 laravel
- javascript - 未捕获的 ReferenceError:tinymce 未在 laravel 中定义
- c - 函数内部的循环似乎在 C 中无法正常工作
- c# - Scripts.Render 抛出“对象未设置为对象的实例”错误
- r - 使用特定年份的人口数据的密度图
- java - 如何在 Java 中使用收集器聚合多个字段