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

相關文章
相關標籤/搜索