在 setTimeout 中调用异步函数

Call async function in setTimeout

我正在尝试将 d3 滑块与 react 一起使用以限制 redux 操作。

我使用下面的代码

export const changeNumber = (number) => (dispatch, getState) => {
  // Clear old timeId
  if (getState().time.timeId !== null) {  
    clearTimeout(getState().time.timeId);
  }
  // Create new timeId
  const timeId = setTimeout(() => {
    
    dispatch(debounceChangeNumber(number));
  }, 1000);
  // refresh to new timeId
  dispatch(updateTimeId(timeId));
  
};

export const debounceChangeNumber = (number) => {
  return {
    type: "CHANGE_NUMBER",
    payload: number,
  };
};

// Throttle redux call, refresh to new timeId
export const updateTimeId = (timeId) => {
  return {
    type: "UPDATE_TIME_ID",
    payload: timeId,
  };
};

在多个动作中使用相同的 timeId 有点困难,如果我使用相同的 timeId 内部动作应该如何异步?喜欢

const timeId = setTimeout(() => {
    // These actions should be asynchronous
    dispatch(debounceChangeNumber(number));
    dispacth(funcA());
    dispacth(funcB());
    ....
  }, 5000);

我真的很想知道这种事情的最佳方法是什么,因为如果我在更大的应用程序中使用它,我必须为每个组件创建新的 timeId 状态。

自己做起来比较复杂,但是对学习很有帮助。

要转发,请使用您已在使用的库中的去抖功能(例如 _.debounce)或获取 useDebounce 挂钩 (https://github.com/xnimorz/use-debounce)

如果您想出于学习目的这样做,这是一个很好的教程:https://davidwalsh.name/javascript-debounce-function