Wednesday 31 May 2017

javascript - 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 (






);

})
);
}


Here is the defined variable inside the constructor:




constructor(props){
super(props);

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

}
}

Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...