繁体   English   中英

无法在 React 中设置未定义的属性“myInterval”

[英]Cannot set property 'myInterval' of undefined in React

当按钮组件调用启动计时器 function 时出现的此错误,有人能帮我解决吗? 我最初使用 componentDidMount 设置它,以便计时器自行启动,但最终希望将其实现为单击按钮启动

如果语句将不胜感激有关如何清理它们的任何其他建议

Cannot set property 'myInterval' of undefined 
class Timer extends React.Component {
  state = {
    seconds: 5,
    stage: "breathIn",
    repetition: 4,
  };

  changeSeconds(x) {
    const { y } = this.state;
    this.setState(({ y }) => ({
      seconds: x,
    }));
  }

  changeStage(x) {
    const { y } = this.state;
    this.setState(({ y }) => ({
      stage: x,
    }));
  }

  changeRepetitions() {
    const { repetition } = this.state;
    this.setState(({ repetition }) => ({
      repetition: repetition - 1,
    }));
  }

  startTimer() {
    this.myInterval = setInterval(() => {
      const { seconds, stage, repetition } = this.state;

      if (seconds > 0) {
        this.setState(({ seconds }) => ({
          seconds: seconds - 1,
        }));
      }

      if (seconds === 0) {
        if (repetition > 0) {
          if (stage === "breathIn") {
            this.changeSeconds(7);
            this.changeStage("hold");
          } else if (stage === "hold") {
            this.changeSeconds(8);
            this.changeStage("breathOut");
          } else if (stage === "breathOut") {
            if (repetition === 2) {
              this.setState(({ repetition }) => ({
                repetition: repetition - 1,
              }));
              this.changeSeconds(5);
              this.changeStage("breathIn");
            } else if (repetition === 1) {
              this.changeSeconds(0);
              this.changeStage("complete");
            }
          }
        } else {
          clearInterval(this.myInterval);
        }
      }
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.myInterval);
  }

  render() {
    const { seconds, stage, repetition } = this.state;
    return (
      <div>
        <Centerbutton startTimer={this.startTimer} />
        <h1>{repetition}</h1>
        <h1>{seconds}</h1>
      </div>
    );
  }
}

export default Timer;
<Centerbutton startTimer={this.startTimer} />

应该是

<Centerbutton startTimer={this.startTimer.bind(this)} />

或者

<Centerbutton startTimer={()=>this.startTimer()} />

这是一个经典的 JS 事件绑定问题

只需将您的 setInterval function 放在componentDidMount生命周期方法中,按照下面的示例,您不能直接在反应中使用 setInterval。

componentDidMount() {
    this.interval = setInterval(() => {
      // Your code here
    }, 1000);
  }
  
  componentWillUnmount() {
    clearInterval(this.interval);
  }

了解有关 setInterval的更多信息,这里是演示应用程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM