首页 > 解决方案 > React 类组件中的“Timer”类型上不存在 this.setinterval

问题描述

我正在尝试使用 reactjs 和 typescript 制作计时器。我的程序中有计时器类组件。我的代码在这里。我想使用myInterval我应该使用setInterval()函数来设置计时器的函数。我面临的问题是 this.myInterval。它表明myIntervalTimer 类型上不存在 。请帮助我。

interface IProps {}

interface IState {
  minutes: number;
  seconds: number;
  isOn: boolean;
}

class Timer extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);
    this.state = {
      minutes: 25,
      seconds: 0,
      isOn: false,
    };

    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
  }

  startTimer() {
    if (this.state.isOn === true) {
      return;
    }

    this.myInterval =  () => setInterval(() => {
      const { seconds, minutes } = this.state;

      if (seconds > 0) {
        this.setState(({ seconds }) => ({
          seconds: seconds - 1,
        }));
      }
      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(this.myInterval);
        } else {
          this.setState(({ minutes }) => ({
            minutes: minutes - 1,
            seconds: 59,
          }));
        }
      }
    }, 1000);
    this.setState({ isOn: true });
  }

  stopTimer() {
    clearInterval(this.myInterval);
    this.setState({ isOn: false });
  }

  resetTimer() {
    this.stopTimer();
    this.setState({
      minutes: 25,
      seconds: 0,
    });
  }

标签: reactjstypescript

解决方案


有两个问题

  1. 您从未为 myInterval 设置字段,因此 this.myInterval 不存在
  2. 您将 a 函数调用设置为 myInterval 而不是 setInterval 的返回

这就是您的代码的外观

  //myInterval field
  myInterval:NodeJS.Timer;

  startTimer() {
    if (this.state.isOn === true) {
      return;
    }

    //Assign the return value from setInterval to myInterval
    this.myInterval = setInterval(() => {
     const { seconds, minutes } = this.state;

      if (seconds > 0) {
        this.setState(({ seconds }) => ({
          seconds: seconds - 1,
        }));
      }
      if (seconds === 0) {
        if (minutes === 0) {
         clearInterval(this.myInterval);
       } else {
         this.setState(({ minutes }) => ({
           minutes: minutes - 1,
           seconds: 59,
         }));
       }
     }
   }, 1000);
   this.setState({ isOn: true });
}

推荐阅读