限制 mobx 存储在数组中只保存 1 个项目

Restricting mobx store to save only 1 item in an array

我正在尝试创建一个定时缓冲区,它只在 mobx 可观察对象中存储 1 个项目。我在商店中调用了一个创建计时器的函数,这样在计时器完成之前,商店中不能保存任何其他项目。然而,如果可能的话,observable 似乎覆盖了这一点。

我正在尝试两件事 ( 定时缓冲区, 数组大小限制器 )

Observable 是否会覆盖标准 javascript 数组 methods/functions?

在 React 的 observable 输出中,我看到一个巨大的数组并且不限于长度 1。

addTourList(node);

这是我的 store.js mobx class。

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;

Do observables override the standard javascript array methods/functions?

他们没有,他们只是将功能扩展到可以使用可观察值的程度。您可能还会遇到一些陷阱,特别是如果您使用的是 Mobx 4.x(docs).

On the output of the observable in React I see a huge array and not restricted to length of 1

如果看到,您一定是在使用 Mobx 4.x。这是正常行为,实际上,如果您检查数组长度,它将被设置为数组中元素的实际数量,因此无需担心。或者只是更新到使用 Proxy 接口的 Mobx 5.x 版本,这样你就会看到你的数组。

例如,您可以随时通过调用 blockTourListMutationFor 函数来阻止对 tourList 变量的任何突变,以设置您想要阻止此变量发生任何突变的毫秒数。

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

我希望这个答案对您有用:)