setInterval中this


  今天使用react做鍾表,自然用到了setInterval,但是出現this指向不明的問題。

 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以前的函數是這樣

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

  這樣使可以的,但是過於繁瑣,觀察了一下,setInterval第一個參數不就是傳一個函數就行嘛,干嘛這么費勁,於是我這樣寫

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

  結果報錯了

  什么?找不到setState,那就是this不對啊,果然setInterval中第一個參數若果是一個裸函數的話,函數中this指向的是window。

  於是改為

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

  完美運行!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM