[英]Why am I getting TypeError: Cannot read property 'now' of undefined
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. 我现在尝试增加以更新ProgressBar。
Your problem is that when you reference 'this' inside the function, this is the function itself not the context outside. 您的问题是,当您在函数内部引用“ this”时,这是函数本身,而不是外部上下文。 If you are using ecmascript you can use an arrow function
如果您使用的是ecmascript,则可以使用箭头功能
this.state = {
now: 0
}
setInterval(() =>{
this.setState({ now: this.state.now + 1});
}, 100);
with an arrow function 'this' have a different meaning. 带有箭头功能“ this”的含义不同。
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 可能当间隔函数运行时'this'的含义与调用setInteval时的含义不同
You might try something like this 您可以尝试这样的事情
this.state = {
now: 0
}
let that = this
setInterval(function () {
that.setState({ now: that.state.now + 1});
}, 100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.