用react写component的时候,经常会遇到this的问题,比如setInterval()这个函数。
下面是一个时钟的例子,是正确的写法
class Clock extends React.Component {
constructor(props){
super(props);
this.state={date:new Date()}
}
componentDidMount(){
setInterval(
function(){
this.updateDate()
}.bind(this),
1000
);
}
updateDate(){
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')
);
容易出错的点有
setInterval(
function(){
this.updateDate()
}.bind(this),
1000
);
这里会遗漏bind(this)
遗漏之后,会报错。
如果不用bind(this)
,也可以用es6写法
setInterval(()=>this.updateDate(),1000)
最好是给setInterval()赋值给一个变量,当该component unmount的时候,取消该定时器。所以更加完善的代码如下。
var timer=setInterval(()=>this.updateDate(),1000);
componentWillUnmount(){
clearInterval(this.timer)
}