Why am I getting this error?
relevant code:
this.state = {
now: 0
}
setInterval(function () {
this.setState({ now: this.state.now + 1});
}, 100);
I am trying to increment now in order to update a ProgressBar.
Your problem is that when you reference 'this' inside the function, this is the function itself not the context outside. If you are using ecmascript you can use an arrow function
this.state = {
now: 0
}
setInterval(() =>{
this.setState({ now: this.state.now + 1});
}, 100);
with an arrow function 'this' have a different meaning.
or you can create a reference outside your context, like this.
this.state = {
now: 0
}
let self = this;
setInterval(function () {
self.setState({ now: self.state.now + 1});
}, 100);
Probably when interval function runs 'this' doesn't means the same as when setInteval was called
You might try something like this
this.state = {
now: 0
}
let that = this
setInterval(function () {
that.setState({ now: that.state.now + 1});
}, 100);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.