如何使用redux中的setTimeout和dispatcher触发定期操作

egu*_*eys 17 javascript flux reactjs redux

我如何/在哪里定期发送行动?使用递归setTimeout进行倒计时.

从示例中得出类似于此的内容:

// Can also be async if you return a function
export function incrementAsync() {
  return dispatch => {
    (function _r() {
      setTimeout(() => {
        // Yay! Can invoke sync or async actions with `dispatch`
        dispatch(increment());
        _r();
      }, 1000);
    })();
  };
}
Run Code Online (Sandbox Code Playgroud)

那么这是一个好主意,还是有更好的方法解决这个问题,比如使用中间件或从其他地方创建动作?

我更喜欢这个的通用版本,我可以通过商店控制计时器的启动/停止.

我已经设置了一个示例实现,请查看https://gist.github.com/eguneys/7023a114558b92fdd25e

Dan*_*mov 17

你建议的方法很好,虽然有点复杂.通常,我会在组件生命周期方法(例如componentDidMount/ componentWillUnmount)中设置间隔,并避免在其他操作上设置间隔的操作.

如果您绝对需要这种灵活性,最好的办法是使用Rx进行异步管理,以及dispatch在可观察链的最末端执行操作.这样您就可以使用Redux(同步更新)并将异步组合留给Rx.