本文介绍了React 中的 clearInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 React 的新手,我试图创建一个带有开始和停止按钮的简单秒表.我正用头撞墙,试图用停止按钮上的 onClick 事件清除间隔.我会为 setInterval 声明一个变量,然后使用 clearInterval 清除它.不幸的是它不起作用.有小费吗?提前致谢.
import React, { Component } from 'react';类 App 扩展组件 {构造函数(道具){超级(道具);this.state = {time:0}this.startHandler = this.startHandler.bind(this);}获取秒(时间){返回`0${time%60}`.slice(-2);}获取分钟(时间){返回 Math.floor(time/60);}开始处理程序(){setInterval(()=>{this.setState({time:this.state.time + 1});},1000)}停止处理程序(){//如何在这里清除间隔????}使成为 () {返回 (<div><h1>{this.getMinutes(this.state.time)}:{this.getSeconds(this.state.time)}</h1><button onClick = {this.startHandler}>START</button><button onClick = {this.stopHandler}>STOP</button><按钮>重置</按钮>
);}}导出默认应用程序;
解决方案
您可以为组件的状态添加间隔,并且可以随时清除它.
componentDidMount(){让 intervalId = setInterval(this.yourFunction, 1000)this.setState({ intervalId: intervalId })}componentWillUnmount(){clearInterval(this.state.intervalId)}
I'm new at React and I was trying to create a simple stopwatch with a start and stop buttons.I'm banging my head against the wall to try to clearInterval with an onClick event on Stop button. I would declare a variable for the setInterval and then would clear it using the clearInterval. Unfortunately it is not working.Any tips?Thank you in advance.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {time:0}
this.startHandler = this.startHandler.bind(this);
}
getSeconds(time){
return `0${time%60}`.slice(-2);
}
getMinutes(time){
return Math.floor(time/60);
}
startHandler() {
setInterval(()=>{
this.setState({time:this.state.time + 1});
},1000)
}
stopHandler() {
//HOW TO CLEAR INTERVAL HERE????
}
render () {
return (
<div>
<h1>{this.getMinutes(this.state.time)}:{this.getSeconds(this.state.time)}</h1>
<button onClick = {this.startHandler}>START</button>
<button onClick = {this.stopHandler}>STOP</button>
<button>RESET</button>
</div>
);
}
}
export default App;
解决方案
you can add interval to your component's state and can clear it whenever you want.
componentDidMount(){
let intervalId = setInterval(this.yourFunction, 1000)
this.setState({ intervalId: intervalId })
}
componentWillUnmount(){
clearInterval(this.state.intervalId)
}
这篇关于React 中的 clearInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!