I have the following React code:
class WarClock extends React.Component{
constructor(props)
{
super(props)
this.state={
dateNow:new Date(),
name:'yakuza'
}
}
componentDidMount(){
this.IntervalID=setInterval(() => this.tick(),1000)
}
componentWillUnmount(){
clearInterval(this.IntervalID);
}
tick(){
console.log(this);
this.setState({dateNow:new Date()})
}
...
If I use this.IntervalID=setInterval(() => this.tick(),1000)
,
the console.log in tick() prints my class object the this component works normally.
However, when I use this.IntervalID=setInterval(this.tick,1000)
, the console.log in tick() prints out the entire 'window' object. As a result, setState() hereby is not found.
Can someone explain why when I use tick function pointer as callback, this is binded with the window object? Isn't my tick() a class function of WarClock? Also, why arrow function will resolve this issue, thanks.