clearInteval在ReactJS的计时器中不起作用

问题描述 投票:0回答:1

我设置了一个简单的计时器,每1秒减少计数1,一旦计数达到零,最终将停止减少计数,当前计时器工作正常,但在达到零后仍将继续减少计数。有人可以告诉我是什么问题吗?

也不确定我是否正确使用componentWillUnmount()生命周期。

代码在下面:

import React, { Component } from "react";

class Timer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 10
    };
  }
  render() {
    const { count } = this.state;
    return <h1>Count:{count} </h1>;
  }
  componentDidMount() {
    this.myTimer = setInterval(() => {
      this.setState({
        count: this.state.count - 1
      });
    }, 1000);
  }
  componentWillUnmount() {
    if (this.state.count === 0) {
      clearInterval(this.myTimer);
    }
  }
}

export default Timer;
reactjs timer components lifecycle
1个回答
0
投票

首先,将setState函数与prevState一起使用,因为您是根据当前状态计算下一个状态的,因此您应像下面这样使用它。

 this.myTimer = setInterval(() => {
      this.setState(prevState => ({
         count: prevState.count - 1
     }));
    }, 1000);

对于componentWillUnmount方法,您可能应该做

componentWillUnmount() {
  if (this.state.count === 0 && this.myTimer) {
    clearInterval(this.myTimer);
  }
}

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.