8

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?

hellogoodnight
  • 1,989
  • 7
  • 29
  • 57

2 Answers2

5

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);
hellogoodnight
  • 1,989
  • 7
  • 29
  • 57
0

Write your functions this way:

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

http://www.react.express/fat_arrow_functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).

ShaTin
  • 2,905
  • 1
  • 19
  • 8