首页 > 解决方案 > (空白)不是函数(React.js)

问题描述

所以我有一个问题,我尝试以给定的时间间隔更改组件的状态,但在测试时,错误:TypeError: this.changeIt is not a function

我不确定为什么会这样。我在构造函数中绑定了函数,调用函数时使用了 this 关键字,但它仍然给我错误。有人可以帮我弄清楚我做错了什么吗?谢谢!

这是我的代码:

import "./timer.css";

import React, { Component } from "react";

var work = new Audio("work.mp3");
let timeRiNow;
var breakTime = new Audio("break.m4a");

export default class TimerBox extends Component {
  constructor(props) {
    super(props);
    this.state = { timeRem: timeRiNow };
    this.handleClick = this.handleClick.bind(this);
    this.refreshPage = this.refreshPage.bind(this);
    this.changeIt = this.changeIt.bind(this);
  }

  refreshPage() {
    window.location.reload();
  }

  changeIt(x) {
    this.setState({ timeRem: x });
  }

  handleClick() {
    let ii = 0;
    if (ii === 1) {
      this.refreshPage();
    }
    ii++;
    var brkmin = 5;
    var brksec = 0;
    var wrkmin = 25;
    var wrksec = 0;

    if (Number(brkmin) == null) {
      brkmin = 0;
    }

    if (Number(brksec) == null) {
      brksec = 0;
    }
    if (Number(wrkmin) == null) {
      wrkmin = 0;
    }
    if (Number(wrksec) == null) {
      wrksec = 0;
    }

    (function myFunc01() {
      //YOUR TIME IN HELL HAS BEGUN

      work.play();
      let iWrk = Number(wrkmin * 60 + wrksec);
      let iBrk = Number(brkmin * 60 + brksec);

      // store the interval id to clear in future
      var intr = setInterval(function () {
        (() => {
          timeRiNow = String(
            new Date(Math.abs(iWrk - 1) * 1000).toISOString().substr(11, 8)
          );
        })();

        this.changeIt(timeRiNow).this.bind();

        console.log(timeRiNow);
        if (--iWrk < 0) {
          clearInterval(intr);

          breakTime.play();

          // store the interval id to clear in future
          var intW = setInterval(function () {
            (() => {
              timeRiNow = String(
                new Date(Math.abs(iBrk - 1) * 1000).toISOString().substr(11, 8)
              );
            })();

            this.changeIt(timeRiNow).this.bind();

            if (--iBrk < 0) {
              clearInterval(intW);
              myFunc01();
            }
          }, 1000);
        }
      }, 1000);
    })();
  }

  render() {
    return (
      <div>
        <center>
          <div className="container">
            <h1 className="neon">
              <span id="neon1">HalfS</span>econd
            </h1>
          </div>

          <center>
            <div id="animationn"></div>
          </center>

          <h2 style={{ color: "#fdf" }}>{this.state.timeRem}</h2>
          <br />
          <br />
          <button className="btn" onClick={this.handleClick} id="yeet">
            Click to Start!
          </button>
        </center>
      </div>
    );
  }
}

标签: javascriptreactjsreact-state

解决方案


推荐阅读