Redux状态管理与类

时间:2016-03-04 15:56:02

标签: javascript timer ecmascript-6 redux

我有一个Timer类,它允许我在JS中暂停/重新启动setInterval

export class Timer {
  constructor(callback, delay) {
    this.callback = callback
    this.delay = delay
    this.remaining = delay
    this.start = undefined
    this.timerId = undefined
  }
  pause() {
    window.clearTimeout(this.timerId)
    this.pauseTime = new Date().getTime()
    this.remaining -= new Date() - this.start
  }
  resume() {
    this.start = new Date().getTime()
    window.clearTimeout(this.timerId)
    this.timerId = window.setTimeout(this.callback, this.remaining)
  }
  quit() {
    window.clearTimeout(this.timerId)
  }
}

My(Bound)Redux Action Creators如下:

export const boundPomodoroStartFinish = () => {
  let id = new Date().getTime()
  let pomodoroTime = 1000
  let timer = new Timer(() => {
    let pomodoro = store.getState().pomodoro
    let time = new Date().getTime()
    store.dispatch(pomodoroFinish(pomodoro, time))
  }, pomodoroTime)
  timer.resume()
  store.dispatch(pomodoroStart(id, timer))
}

export const boundPomodoroPause = () => {
  let pomodoro = store.getState().pomodoro
  let time = new Date().getTime()
  pomodoro.timer.pause()
  store.dispatch(pomodoroPause(time))
}

export const boundPomodoroQuit = () => {
  let pomodoro = store.getState().pomodoro
  let time = new Date().getTime()
  pomodoro.timer.quit()
  store.dispatch(pomodoroQuit(pomodoro, time))
}

export const boundPomodoroResume = () => {
  let pomodoro = store.getState().pomodoro
  pomodoro.timer.resume()
  store.dispatch(pomodoroResume())
}

感觉我不应该在绑定的Action Creators中调用pomodoro.timer.x(),而应该将pomodoro发送到reducers并让reducers调用该动作。

或者,我可以完全摆脱课程并将整个setInterval时间管理放入store并让减速器始终在那里计算它并且只在那里(在调用适当的动作之后) - 但这似乎比必要的更复杂。

Redux的做事方式是什么?谢谢!

1 个答案:

答案 0 :(得分:0)

这也是新的,但我认为你应该考虑为此创建一个Redux中间件。

http://redux.js.org/docs/advanced/Middleware.html

其中一个示例使用clearTimeout。