在react中使用setInterval

在react组件内使用setInterval定时执行某个方法,

在状态初始化时设定一个state{timer:null}

在componentDidMount方法中设置定时执行的方法

this.state.timer=setInterval(()=>{

//需要定时执行的方法

}, 500)

在componentWillUnmount方法中要对定时器进行销毁

if(this.state.timer!= null) {

clearInterval(this.state.timer);

}

你可能感兴趣的:(在react中使用setInterval)