我的代码如下
/**
* @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;