Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: 'this.state' is undefined inside a component function

I'm having trouble accessing this.state in functions inside my component. I already found this question on SO and added the suggested code to my constructor:

class Game extends React.Component {

  constructor(props){
    super(props);
    ...
    this.state = {uid: '', currentTable : '', currentRound : 10, deck : sortedDeck};
    this.dealNewHand = this.dealNewHand.bind(this);
    this.getCardsForRound = this.getCardsForRound.bind(this);
    this.shuffle = this.shuffle.bind(this);
  }

  // error thrown in this function
  dealNewHand(){
    var allCardsForThisRound = this.getCardsForRound(this.state.currentRound); 
  }

  getCardsForRound(cardsPerPerson){
    var shuffledDeck = this.shuffle(sortedDeck);
    var cardsForThisRound = [];
    for(var i = 0; i < cardsPerPerson * 4; i++){
      cardsForThisRound.push(shuffledDeck[i]);
    }
    return cardsForThisRound;
  }

  shuffle(array) {
    ...
  }

  ...
  ...

It still does not work. this.state.currentRound is undefined. What is the problem?

like image 558
hellogoodnight Avatar asked May 11 '16 14:05

hellogoodnight


1 Answers

I came up with something that worked. I changed the code for binding getCardsForRound in the constructor to:

this.getCardsForRound = this.getCardsForRound.bind(this, this.state.currentRound);
like image 188
hellogoodnight Avatar answered Nov 05 '22 23:11

hellogoodnight