setInterval中this

  今天使用react作钟表,天然用到了setInterval,可是出现this指向不明的问题。html

 1 <html>
 2 <head>
 3 <meta charset="UTF-8" />
 4 <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
 5 <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
 6 <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
 7 </head>
 8 <body>
 9 
10 <div id="example"></div>
11 <script type="text/babel">
12 class Clock extends React.Component { 13  constructor(props) { 14  super(props); 15     this.state = {date: new Date()}; 16  } 17 
18  componentDidMount() { 19     this.timerID = setInterval( 20       () => this.tick(), 21       1000
22  ); 23  } 24 
25  componentWillUnmount() { 26     clearInterval(this.timerID); 27  } 28 
29  tick() { 30     this.setState({ 31       date: new Date() 32  }); 33  } 34 
35  render() { 36     return ( 37       <div>
38         <h1>Hello, world!</h1>
39         <h2>如今是 {this.state.date.toLocaleTimeString()}.</h2>
40       </div>
41  ); 42  } 43 } 44 
45 ReactDOM.render( 46   <Clock />,
47   document.getElementById('example') 48 ); 49 </script>
50 
51 </body>
52 </html>

  在componentDidMount中setInterval使用了ES6的箭头函数,有建议能够使用ES6之前的函数是这样react

1 let that = this; 2 this.timerID = setInterval(function () { 3   return that.tick(); 4 },1000);

  这样使能够的,可是过于繁琐,观察了一下,setInterval第一个参数不就是传一个函数就行嘛,干吗这么费劲,因而我这样写babel

1 this.timerID = setInterval( 2   this.tick, 3 1000);

  结果报错了dom

  什么?找不到setState,那就是this不对啊,果真setInterval中第一个参数若果是一个裸函数的话,函数中this指向的是window。函数

  因而改成this

1 this.timerID = setInterval( 2   this.tick.bind(this), 3 1000);

  完美运行!spa

相关文章
相关标签/搜索