超时在组件上未清除将卸载



我试图在组件渲染时设置一个计时器(componentDidMount(,但是,如果用户在时间结束前完成了给定的任务,我希望计时器停止(在componentWillUnmount中(,但它不会。时间结束后,警报会在其他页面上弹出。

class questionstest extends Component {
constructor(props) {
timer: null
};
componentDidMount() {
this.beginTimer();
}
beginTimer() {
this.setState({timer:setTimeout(() => alert("time end"), 100000)});
}
componentWillUnmount() {
clearTimeout(this.timer)
}

注意:试图移动";clearTimeout(this.timer(";提交按钮,但它没有工作,我还确保";componentWillUnmount";被调用。

注意2:如果有人能告诉我在我从服务器上获得数据后如何启动计时器,那就太好了。

将代码更新为:

class questionstest extends Component {
constructor(props) {
this.state = {
timer: null
}
}
componentDidMount() {
this.beginTimer();
}
beginTimer() {
this.setState({timer:setTimeout(() => alert("time end"), 100000)});
}
componentWillUnmount() {
clearTimeout(this.state.timer)
}
}

尽管如此,您似乎不需要定时器处于状态,因为更新DOM不需要定时器更新,因此您也可以使用以下解决方案:

class questionstest extends Component {
constructor(props) {
this.timer = null;
};
componentDidMount() {
this.beginTimer();
}
beginTimer() {
this.timer = setTimeout(() => alert("time end"), 100000);
}
componentWillUnmount() {
clearTimeout(this.timer);
}
}

尝试clearTimeout(this.state.timer)

最新更新