简体   繁体   English

在Redux中应用受限制的中间件

[英]Apply a throttled middleware in redux

I am creating a small middleware for redux. 我正在为redux创建一个小型中间件。 Since my electron application connects to another database and updates it's state (so that I may see the state of this application on my main application). 由于我的电子应用程序连接到另一个数据库并更新了它的状态(因此我可以在主应用程序上看到该应用程序的状态)。 Here is my basic code: 这是我的基本代码:

const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];

export remoteMiddleware => store => next => action => {
  const db = MongoClient.connect(process.env.MONGO_URL);
  try {
    if (!BLACKLIST.includes(action.type)) {
      const state = store.getState();
      db.collection('state').update(
        { _id: process.env.APP_ID },
        { $set: { state } }
      )
    }
  } finally {
    db.close();
  }
}

However, I am having a bit of a problem where this is firing TOO often, when it doesn't always need to fire immediately. 但是,我有一个问题,那就是它经常触发TOO,而不必总是立即触发。 I would prefer if it fired every n iterations, or perhaps no more than x ms. 我希望它每n次迭代触发一次,或者不超过x ms。

Is there a way to throttle a redux middleware so that it will only fire every n times, or such that it will only run every x number of ms? 有没有一种方法可以限制redux中间件,使其仅每n次触发一次,或仅每x毫秒运行一次?

How about simply 怎么样

const BLACKLIST = ['redux-form/FOCUS ', 'redux-form/BLUR'];
var lastActionTime = 0;

export remoteMiddleware => store => next => action => {
  let now = Date.now();
  try {
    if (!BLACKLIST.includes(action.type) && now - lastActionTime > 100)
    ...
  } finally() {
    lastActionTime = now;
    db.close();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM