首页 > 解决方案 > 反应 setTimeout 钩子 onclick

问题描述

当我单击下一个按钮时,它给出了一个错误无法读取未定义的属性“handleCheck”。任何人都可以帮忙吗?在此先感谢

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = { check: false };
  handleCheck = () => {
    console.log("hello");
    this.setState({ check: !this.state.check });
  };
  componentDidMount() {
    setTimeout(() => {
      this.handleCheck();
    }, 10000);
  }
  timer() {
    setTimeout(() => {
      this.handleCheck();
    }, 10000);
  }
  render() {
    return (
      <div>
        <p>hello</p>
        {this.state.check ? (
          <button onClick={this.timer}>Next</button>
        ) : (
          <div>button not showing </div>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("container"));

标签: javascriptreactjsonclickreact-hooksstate

解决方案


timer也应该是一个箭头函数来引用正确的this

timer = () => {
    setTimeout(() => {
      this.handleCheck();
    }, 10000);
  }

解决此问题的另一种方法是绑定thistimer.

而且由于新状态依赖于旧状态,所以handleCheck函数应该是这样的:

handleCheck = () => {
    console.log("hello");
    this.setState(prevState => ({ check: !prevState.check }));
  };

推荐阅读