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