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

问题描述 投票:1回答:1

当我实现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)
  }
}
redux middleware
1个回答
1
投票

假设链中的所有其他中间件正确执行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();
© www.soinside.com 2019 - 2024. All rights reserved.