xoomer xoomer - 5 months ago 31
Javascript Question

ReactJS : this.setState is not a function?

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.

Answer

Yes 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);
}