admin管理员组文章数量:1393866
I am new to ReactJS and I am having an error "this.setState is not a function".
constructor() {
super();
this.state = {
visible: false,
navLinesShow: true
};
this.navOpen = this.navOpen.bind(this)
}
navOpen() {
this.setState({
navStatus: "navShow",
navLinesShow: false
});
if ( this.state.visible === false) {
setTimeout(function (){
this.setState({
visible: true
});
}, 3000);
}
I have added this.navOpen = this.navOpen.bind(this) to the contructor. So I guess the problem is with setTimeout function.
What is a possible fix?
Thank You.
I am new to ReactJS and I am having an error "this.setState is not a function".
constructor() {
super();
this.state = {
visible: false,
navLinesShow: true
};
this.navOpen = this.navOpen.bind(this)
}
navOpen() {
this.setState({
navStatus: "navShow",
navLinesShow: false
});
if ( this.state.visible === false) {
setTimeout(function (){
this.setState({
visible: true
});
}, 3000);
}
I have added this.navOpen = this.navOpen.bind(this) to the contructor. So I guess the problem is with setTimeout function.
What is a possible fix?
Thank You.
Share Improve this question asked Jun 30, 2016 at 13:15 xoomerxoomer 3212 gold badges11 silver badges22 bronze badges3 Answers
Reset to default 6Yes the problem is the setTimeout inside the setTimeout function "this" refer to the function itself: so the solution is the typical var that = this
:
navOpen() {
this.setState({
navStatus: "navShow",
navLinesShow: false
});
if ( this.state.visible === false) {
var that = this;
setTimeout(function (){
that.setState({
visible: true
});
}, 3000);
}
It is because this
doesn't have the correct value due to runtime binding. You need to use lexical binding. The best solution is to use ES6
arrow functions () => {}
which provides lexical binding of this value. Even with the setTimeout()
the lexical binding of this would fix the error you are getting
constructor() {
super();
this.state = {
visible: false,
navLinesShow: true
};
}
navOpen = () => {
this.setState({
navStatus: "navShow",
navLinesShow: false
});
if ( this.state.visible === false) {
setTimeout(() => {
this.setState({
visible: true
});
}, 3000);
}
}
Another solution in addition to @pinturic's solution is to use ES6 arrow functions. If you're using ES6/Babel, etc., you can use an arrow function to bind to the lexical this
.
navOpen() {
this.setState({
navStatus: "navShow",
navLinesShow: false
});
if (!this.state.visible) {
setTimeout(() => this.setState({visible: true}), 3000);
}
}
本文标签: javascriptReactJSthissetState is not a functionStack Overflow
版权声明:本文标题:javascript - ReactJS : this.setState is not a function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744083227a2588038.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论