如何使用 redux 和 redux/toolkit 制作一个倒计时器?

我的代码如下

/**
 * @file: timerSlice
 */
import { createSlice } from '@reduxjs/toolkit';
import { toast } from 'native-base';
import { checkMax } from '~/utils/check';

const INITIAL_TIME = 5 * 60 * 1000;
const ONE_MINUTE = 60 * 1000;
const FIVE_MINUTE = 5 * 60 * 1000;
const INTERVAL_TIME = 500;
/**
 * 初始state
 */
const initialState = {
  time: INITIAL_TIME,
  endTime: INITIAL_TIME,
  countingId: null,
};

export const timerSlice = createSlice({
  name: 'timer',
  initialState,
  reducers: {
    setTime(state, action) {
      state.time = action.payload;
    },
    increment1Minute(state) {
      state.time += ONE_MINUTE;
    },
    decrement1Minute(state) {
      const _time = checkMax(state.time - ONE_MINUTE, 0);
      state.time = _time;
    },
    increment5Minute(state) {
      state.time += FIVE_MINUTE;
    },
    decrement5Minute(state) {
      const _time = checkMax(state.time - FIVE_MINUTE, 0);
      state.time = time;
    },
    // get last time
    tick(state) {
      state.time = state.endTime - Date.now();
    },
    countDown(state) {
      const now = Date.now();
      state.endTime = now + state.time;
      state.countingId = setInterval(() => {
        const _time = state.endTime - Date.now();
        if (_time <= 0) {
          clearInterval(state.countingId);
          state.countingId = null;
          state.time = INITIAL_TIME;
          state.endTime = INITIAL_TIME;
          toast.show({
            title: 'end.timer',
          });
        }
      }, INTERVAL_TIME);
    },
    pulse(state) {
      if (state.countingId) {
        clearInterval(state.countingId);
      }
      // reset
      state.endTime = Date.now() + state.time;
    },
    // 重置
    reset(state, action) {
      if (state.countingId) {
        clearInterval(state.countingId);
        state.countingId = null;
      }
      state.time = INITIAL_TIME;
    },
  },
});
// Action creators are generated for each case reducer function
export const { setTime, increment1Minute, decrement1Minute, increment5Minute, decrement5Minute, reset, countDown } =
  timerSlice.actions;

export default timerSlice.reducer;




阅读 809
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题