Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
  }
}
like image 307
Eugen Sunic Avatar asked Dec 04 '22 23:12

Eugen Sunic


1 Answers

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);
like image 200
zurfyx Avatar answered Dec 11 '22 16:12

zurfyx