首页 > 解决方案 > 限制 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;

标签: reactjsstoremobx

解决方案


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);

我希望你觉得这个答案有用:)


推荐阅读