繁体   English   中英

带类的Redux状态管理

[英]Redux state management with class

我有一个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)
  }
}

我的(绑定)Redux动作创建者如下:

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() ,而应该将番茄发送给reducers并让reducers调用该动作。

或者,我可以完全摆脱该类,并将整个setInterval时间管理放入store并让reducers始终仅在此处(在调用适当的操作之后)在其中进行计算-但这似乎比必需的更为复杂。

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

这也是新手,但我认为您应该考虑为此创建Redux中间件。

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

示例之一使用clearTimeout。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM