我设定了一个时间间隔
componentDidMount()
并保存到我的应用程序状态。
计时器正确启动,但我无法在需要时清除它。这是初始状态:
this.initialState = {
score: 0,
finished: false,
currentQuestion: 0,
questions: [],
minutes: 1,
seconds: 15,
timer: 0
};
动作看起来像这样。它接收定时器(间隔)作为参数:
export function updateTimer(timer) {
return {
type: UPDATETIMER,
payload: {
timer
}
}
}
我在我的
reducers.js
:
function timer(state = 0, action = {}) {
switch(action.type) {
case RESTART:
return 0;
case UPDATETIMER:
if(action.payload.timer !== undefined){
return action.payload.timer;
}else {
clearInterval(state);
return 0;
}
default:
return state;
}
}
在app.js中,我这样使用它:
<Navbar
onUpdateTimer= {
(timer) => {
this.props.dispatch(updateTimer(timer))
}
}
/>
我试图做的是,如果我的调用有一个参数,它设置间隔,如果没有,它清除它。
调用该操作的组件如下:
import React from 'react';
export default class CountDown extends React.Component {
constructor(props) {
super(props);
this.startTimer = this.startTimer.bind(this);
this.countDown = this.countDown.bind(this);
}
startTimer() {
this.props.onUpdateTimer(setInterval(this.countDown, 1000));
}
countDown() {
let minutes = this.props.minutes;
let seconds = this.props.seconds - 1;
if (seconds === 0) {
if(minutes !== 0){
minutes -=1;
seconds = 59;
}else {
this.props.timeUp()
setTimeout(function(){
alert("SE HA ACABADO EL TIEMPO");
},0);
}
}
this.props.onUpdateTime(minutes, seconds);
}
render() {
return (
<div id="clockdiv">
<span className="minutes">{this.props.minutes} : </span>
<span className="seconds">{this.props.seconds}</span>
</div>
);
}
componentDidMount(){
this.startTimer();
}
}
我用得对吗
clearInterval(state)
在action creator函数中?