简体   繁体   English

使用 Redux 创建倒数计时器

[英]Creating a countdown timer with Redux

I want to create a timer that will indicate a flash message (“Saved!”) to be shown for a given duration value, eg 30 seconds.我想创建一个计时器,该计时器将指示要在给定的持续时间值(例如 30 秒)内显示的闪现消息(“已保存!”)。

My thinking how to accomplish this with Redux goes like this:我的想法是如何使用 Redux 来实现这一点:

  1. The countdown is fired.倒计时被触发。
  2. Every second, the TIMER_TICK action type is sent to the reducer.每一秒, TIMER_TICK动作类型都会被发送到减速器。
  3. When the duration value (in seconds) is reached, the timer should be cleared.当达到持续时间值(以秒为单位)时,应清除timer
const initialState = {
  count: 0,
  timerOn: false,
}

const tick = () => ({ type: TIMER_TICK });

let timer = null;

export const startFlashMessageTimer = () => dispatch => {
  clearInterval(timer);
  timer = setInterval(() => dispatch(tick()), 1000);
}

But I'm stuck at where to put the logic that checks if the count value is reached (30 in this case).但我被困在何处放置检查是否达到计数值的逻辑(在这种情况下为 30)。 Any suggestion how/where I solve this?任何建议我如何/在哪里解决这个问题?

Something like this?像这样的东西?

export const startFlashMessageTimer = () => (dispatch, getState) => {
  let timer = null;
  clearInterval(timer);
  timer = setInterval(() => {
      dispatch(tick());
      const { count } = getState();
      if (count >= 5) { clearInterval(timer) }
  }, 1000);
}

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

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