【问题标题】:Why is my 'setInterval' function unable repeatedly call the 'tick()' function? (react.js)为什么我的 'setInterval' 函数无法重复调用 'tick()' 函数? (反应.js)
【发布时间】:2020-06-18 06:47:01
【问题描述】:

我试图了解发生了什么,发现在 tick() 函数中使用箭头函数可以解决问题,但我不明白为什么。有人可以解释一下吗?

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

    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = { date: new Date() };
      }
      componentDidMount() {
        setInterval(this.tick(), 1000);
      }
      tick() {
        this.setState({ date: new Date() });
      }
      render() {
        return (
          <div>
            <h1>Hello, World</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        );
      }
    }

    ReactDOM.render(<Clock />, document.getElementById("root"));

【问题讨论】:

  • I don't understand why. Can someone pls explain? the following 可能会有所帮助。

标签: reactjs class callback this


【解决方案1】:

你需要在构造函数中绑定你的tick函数。

constructor(props) {
    super(props);
    this.state = { date: new Date() };
    this.tick = this.tick.bind(this); // here
  }

并且不要忘记清除componentWillUnmount生命周期中的间隔

【讨论】:

    【解决方案2】:

    setInterval 函数和 this 关键字:

    setInterval 在与类不同的上下文中运行。所以在 setInterval 中,'this' 关键字并不指向类,而是引发 setInterval 的事件。因此,当您使用 =>(胖箭头符号)定义它时,“this”关键字会“自动绑定”到包含它的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2022-10-04
      • 2017-12-27
      • 2019-08-03
      • 1970-01-01
      相关资源
      最近更新 更多