如何在redux“timeoutScheduler”中间件文档示例中使用取消功能?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在redux“timeoutScheduler”中间件文档示例中使用取消功能?相关的知识,希望对你有一定的参考价值。

当我实现MW它工作得很好但如果我想清除超时怎么调用“取消”功能呢?这是代码:(taken from Redux middleware

   /**
 * 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)
  }
}
答案

假设链中的所有其他中间件正确执行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();

以上是关于如何在redux“timeoutScheduler”中间件文档示例中使用取消功能?的主要内容,如果未能解决你的问题,请参考以下文章