注意点
1、定时器中this一般指向为window对象
2、react箭头函数中定时器中也可以使用this,为当前class对象
实践:
1、定时器赋值给全局变量,异步动作后清除
class TopoPanel extends Component {
constructor(props) {
}
startGetTopoDataInterval = () => {
this.startGetTopoDataInterval = setInterval(this.getTopoDataIntervalTask,1000);
}
getTopoDataIntervalTask = () =>{
let isDataOK = this.getTopoDataAndSetState();
if (isDataOK) {
this.clearGetTopoDataInterval();
}
}
clearGetTopoDataInterval = () => {
clearInterval(this.startGetTopoDataInterval);
}
getTopoDataAndSetState = () => {
let cacheData = xxx;
if (cacheData) {
xxx;
}
else {
xxx;
return false;
}
return true;
}
}
2、定时器定义为局部变量
class Panel extends Component {
constructor(props) {
}
startDrawLoadInterval = (loadData) => {
let drawLoadInterval = setInterval((loadData)=>{
if (xxx) {
xxx;
clearInterval(drawLoadInterval);
}
},1000);
}
}