hellogoodnight
hellogoodnight

Reputation: 2129

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?

Upvotes: 8

Views: 11831

Answers (2)

ShaTin
ShaTin

Reputation: 3075

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

Upvotes: 0

hellogoodnight
hellogoodnight

Reputation: 2129

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

Upvotes: 5

Related Questions