Reactjs redux中的Debounce API调用

Reactjs redux中的Debounce API调用,reactjs,google-analytics,redux,react-redux,redux-thunk,Reactjs,Google Analytics,Redux,React Redux,Redux Thunk,我试图发送分析数据到谷歌,需要作出一个API。我有一个搜索框,可以过滤客户列表。搜索本身每300毫秒取消一次公告,但我只想每1000毫秒向GA发送一次搜索数据 我正在尝试使用中间件。但我注意到这只会延迟状态的更新。我试着用redux thunk来使用它。我尝试了已经写在那里的东西,但没有成功 这就是我的thunk和middle产品的样子 let store = createStore( reducers, applyMiddleware(logger, createDebounce(),

我试图发送分析数据到谷歌,需要作出一个API。我有一个搜索框,可以过滤客户列表。搜索本身每300毫秒取消一次公告,但我只想每1000毫秒向GA发送一次搜索数据

我正在尝试使用中间件。但我注意到这只会延迟状态的更新。我试着用redux thunk来使用它。我尝试了已经写在那里的东西,但没有成功

这就是我的thunk和middle产品的样子

let store = createStore(
  reducers,
  applyMiddleware(logger, createDebounce(), thunkMiddleware)
);

export function trackCustomerSearch(key) {
  const thunk = dispatch => {
    console.log(key); //This should be only logged only once for 1000ms
    ... //make api call to GA
  };

  thunk.meta = {
    debounce: {
      time: 1000
    }
  };

  return thunk;
}

我错过什么了吗?或者有其他方法吗?

是时候编写自己的中间件了。这并不难,你可以让它完全按照你的意愿去做

const debounceInterval = 1000;
let timerRef = null;

const updateGAMiddleware = store => next => action => {
  if (action.type === 'USER_UPDATED_SEARCH_FIELD') {
    // if my timeout hasn't passed, exit early
    if (timerRef) return next(action);

    // send update to GA here
    // (presumably search field value is in action.data)

    timerRef = setTimeout(() => { timerRef = null; }, debounceInterval); 
  }
  return next(action);
};

export default updateGAMiddleware;
然后,您只需导入并包括该中间件,如-a-so:

...
import updateGAMiddleware from './<somewhere_sane>';
let store = createStore(
  reducers,
  applyMiddleware(logger, updateGAMiddleware, thunkMiddleware)
);
。。。
从“/”导入更新中间件;
let store=createStore(
减速器,
applyMiddleware(记录器、更新中间件、Thunk中间件)
);
然后您可以根据需要调度
USER\u UPDATED\u SEARCH\u FIELD
操作,因为它们最多每秒发送一次给GA

我不知道你是否还需要另一个去公告的中间件。如果您只关心您发布到GA的频率,而不关心您更新状态树的频率,那么您可能不关心

希望这就是你想要的。如果没有,请澄清,我将尽我所能提供帮助。否则,祝你好运