2
我正在做一个倒计时器作为一个React练习(对于我自己,而不是一个类或任何东西),并且一切正常(尽管笔记总是受欢迎),除了我注意到它会继续计数即使在卸载组件后也是如此。停止组件中的计时器
所以现在我想让它停止卸载,但似乎无法做到正确。在卸载时停止setInterval
的协议是什么?以下是我的:
class TimerVal extends Component {
constructor(props) {
super(props)
this.state = {
timeToGo: 30
}
}
secondsToMMSS(seconds) {
//returns "mm:ss"
}
componentDidMount() {
setInterval(
() => this.setState({
timeToGo: this.state.timeToGo - 1
}),
1000
)
}
componentWillUnmount() {
() => this.setState({
timeToGo: undefined
})
}
render() {
// styles
console.log(this.state)
const count = (this.state.timeToGo > 0) ? this.secondsToMMSS(this.state.timeToGo) : "00:00"
console.log(count)
return(
<div style={timerStyle}>
<span style={timerSpanStyle}>
{count}
</span>
</div>
);
}
}