This.setState to setTimeout in react
Function to update the state:
animate() {
setInterval(function(){
setTimeout( this.setState({
a: '123'
}), 1000);
}, 4000);
}
Method:
componentDidMount() {
this.animate();
}
Mistake:
Uncaught TypeError: this.setState is not a function
Then the following code tried:
animate() {
setInterval(function(){
setTimeout( () => {this.setState({
a: '123'
})}, 1000);
}, 4000);
}
And the following error:
Uncaught TypeError: _this2.setState is not a function
source to share
The problem stems from your definition setInterval
.
When you execute setInterval(function() {...})
, the keyword is this
no longer bound to the React component, but to the function that it calls internally, due to the introduction of the new scope.
You can switch it to:
animate() {
const self = this
setInterval(function() {
setTimeout(() => self.setState({ a: '123' }), 1000)
}, 4000)
}
This is self
how the value of the React component is assigned this
before the new scope is introduced, or you can use all arrow functions to store the keyword this
referencing the component:
animate() {
setInterval(() => {
setTimeout(() => this.setState({ a: '123' }), 1000)
}, 4000)
}
source to share