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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With