如何在 redux "timeoutScheduler" 中间件文档示例中使用取消功能?
How to use the cancel function in redux "timeoutScheduler" middleware docs example?
当我实现 MW 时效果很好,但我如何调用 "cancel" 函数
如果我想清除超时?
这是代码:(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()
的调用将 return 这个 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();
当我实现 MW 时效果很好,但我如何调用 "cancel" 函数 如果我想清除超时? 这是代码:(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()
的调用将 return 这个 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();