【发布时间】: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