eugen_sunic eugen_sunic - 1 year ago 67
Javascript Question

this.setState makes variable undefined?

I'm trying to increment my state variable, but whenever I do so an error pops up which says that the variable state is undefined. I defined my variable inside the constructor. Obviously something is going on in the setState function.

Here is the code which renders an error:

displayDiv(){
var arr=[];
if (this.state.flag[2]){
this.setState({counter:counter+4}); // error:undefined
for (let i = this.state.counter-4; i < this.state.counter; i++)
arr.push(this.state.arrayHeader[0].content);
}
}
return(
arr.map(function(item,i){
return (
<div className="bodydiv col-sm-3">
<Header/>
<Content/>
<Tags/>
</div>
);

})
);
}


Here is the defined variable inside the constructor:

constructor(props){
super(props);

this.state = {
arrayHeader:[],
arraytag1:[],
arraytag2:[],
counter:0,
flag:[false,false,false]
}
}

Answer Source

Your counter +4 points nowhere.

It should be this.state.counter + 4

Also, if you are calling this function on the render() make sure it has been previously binded, you can do that like this on the constructor:

this.displayDiv = this.displayDiv.bind(this);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download