2017-08-02 42 views
3

函数来更新状态:this.setState中的setTimeout在反应

animate() { 
setInterval(function(){ 
    setTimeout(this.setState({ 
    a: '123' 
    }), 1000); 
}, 4000); 
} 

调用的方法:

componentDidMount() { 
    this.animate(); 
} 

错误:

Uncaught TypeError: this.setState is not a function 

然后下一个代码的尝试:

animate() { 
setInterval(function(){ 
    setTimeout(() => {this.setState({ 
    a: '123' 
    })}, 1000); 
}, 4000); 
} 

而下一个错误是:从您的setInterval定义

Uncaught TypeError: _this2.setState is not a function 

回答

2

的问题造成的。

当您做setInterval(function() {...})时,this关键字不再绑定到React组件,而是绑定到它在内部调用的函数,因为引入了新的作用域。

您可以切换到:

animate() { 
    const self = this 

    setInterval(function() { 
    setTimeout(() => self.setState({ a: '123' }), 1000) 
    }, 4000) 
} 

这样self是分配到的this的阵营成分值引入新的范围之前,或者您可以使用所有箭头功能保留this关键字引用组件:

animate() { 
    setInterval(() => { 
    setTimeout(() => this.setState({ a: '123' }), 1000) 
    }, 4000) 
} 
0

虽然提交m_callens答案是正确的,我会用bind以及添加了这种可能性,对于那些谁使用预ES6 JavaScript。

animate() { 
    setInterval((function(){ 
     setTimeout((function() {this.setState({ 
      a: '123' 
     })}).bind(this), 1000); 
    }).bind(this), 4000); 
} 
相关问题