redux - 如何在 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)
}
}
解决方案
假设链中的所有其他中间件都正确执行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();
推荐阅读
- node.js - 使用 Node Js 通过 shell 将文件保存在 gcloud 中。错误:“目标文件夹必须存在”、“目标文件夹必须是可写的”
- swift - 中心图像并快速添加背景
- node.js - Chart.JS 图表左上角被一些可视化的nodejs挡住了
- reactjs - 如何保存每个用户事务的 redux 状态
- c# - Mini-profiler 不显示任何关于 sql 查询的统计信息?
- python - 将整数转换为时间格式
- python-3.x - Pandas 将列的所有值替换为仅一组的平均值
- javascript - hasClass 不工作。当出现“活动卡”类时,我尝试将类添加到 div 中。有任何想法吗?
- python - Python如何根据另一个csv-pandas在一个csv中搜索值?
- google-cloud-platform - 由 API 创建时电子表格的位置