class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
在上面的代码中-我无法理解setInterval()行-确切地说,是setInterval行的function参数。我认为这是一个箭头功能-我可能错了。我将其替换为常规函数setInterval(function(){this.tick()},1000)
,并收到一条错误消息,指出tick()不是函数。这里发生了什么事?
this
引用在使用旧式function()
语法时被重置,而对于=>
(箭头功能),this
引用被保留。您仍然可以使用function()
,但需要调用.bind(this)
来“修复” this
参考。
所以这个:
this.timerID = setInterval(
() => this.tick(),
1000
);
等效于此:
this.timerID = setInterval(
function() { this.tick(); }.bind(this),
1000
);
您需要这样做,因为setTimeout
/ setInterval
是global
(window
)对象的成员属性,因此在setTimeout
或setInterval
回调中,this
引用用于window
,而不是呼叫站点的this
。