当我实现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();