首页 > 解决方案 > 如何在 redux“timeoutScheduler”中间件文档示例中使用取消功能?

问题描述

当我实现 MW 时效果很好,但是如果我想清除超时,如何调用“取消”功能?这是代码:(取自 Redux 中间件

   /**
 * Schedules actions with { meta: { delay: N } } to be delayed by N milliseconds.
 * Makes `dispatch` return a function to cancel the timeout in this case.
 */
const timeoutScheduler = store => next => action => {
  if (!action.meta || !action.meta.delay) {
    return next(action)
  }
​
  const timeoutId = setTimeout(
    () => next(action),
    action.meta.delay
  )
​
  return function cancel() {
    clearTimeout(timeoutId)
  }
}

标签: reduxmiddleware

解决方案


假设链中的所有其他中间件都正确执行return next(action),那么您的调用dispatch()将返回此cancel函数。例如:

const cancel = store.dispatch({type : "INCREMENT", meta : {delay : 1000}});

// kill it off
cancel();

或者,与 React 组件中的绑定动作创建者类似:

// assume we have an action creator like this passed to connect():
function incrementWithDelay() {
    return {type : "INCREMENT", meta : {delay : 1000}};
}


const cancel = this.props.incrementWithDelay();
cancel();

推荐阅读