class Clock extends React.Component{
constructor(props){
super(props);
this.state = {date:new Date()};
}
trick(){
this.setState({date:new Date()});
}
componentDidMount(){
this.timeId = setInterval(
()=>this.trick(),1000);
}
componentWillUnmount(){
clearInterval(this.timeId)
}
render(){
return <div>
<h1>現在是{this.state.date.toLocaleTimeString()}</h1>
</div>;
}
}
上面的是仿照列子的正確寫法,但由於好奇心,我將裏面的
componentDidMount(){ this.timeId = setInterval( ()=>this.trick(),1000); }中的this.timeId = setInterval( ()=>this.trick(),1000); 進行了改動寫成了this.timeId = setInterval(this.trick,1000)後,再次運行發現失去了計時器的效果,查閱後得知是因爲this指向問題
this工作原理http://bonsaiden.github.io/JavaScript-Garden/zh/#function.this
再進行進一步改造(在構造函數綁定了this)
class Clock extends React.Component{
constructor(props){
super(props);
this.state = {date:new Date()};
this.trick = this.trick.bind(this);
}
trick(){
this.setState({date:new Date()});
}
componentDidMount(){
this.timeId = setInterval(this.trick,1000);
}
componentWillUnmount(){
clearInterval(this.timeId)
}
render(){
return <div>
<h1>現在是{this.state.date.toLocaleTimeString()}</h1>
</div>;
}
}
簡而言之,就是this指代造成的問題,具體this指代什麼可以通過console.log(this)輸出到瀏覽器控制檯查看