Function to update state:
animate() {
setInterval(function(){
setTimeout( this.setState({
a: '123'
}), 1000);
}, 4000);
}
The method called:
componentDidMount() {
this.animate();
}
Error:
Uncaught TypeError: this.setState is not a function
Then the next code tried:
animate() {
setInterval(function(){
setTimeout( () => {this.setState({
a: '123'
})}, 1000);
}, 4000);
}
And the next error was:
Uncaught TypeError: _this2.setState is not a function
The problem stems from your definition of setInterval
.
When you do setInterval(function() {...})
, the this
keyword is no longer bound to the React component but to the function it is called within because of the introduction of the new scope.
You can either switch it to:
animate() {
const self = this
setInterval(function() {
setTimeout(() => self.setState({ a: '123' }), 1000)
}, 4000)
}
This way self
is assign to the React component value of this
before the new scope is introduced, or you can use all arrow functions to preserve the this
keyword referencing the component:
animate() {
setInterval(() => {
setTimeout(() => this.setState({ a: '123' }), 1000)
}, 4000)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With