2016-05-11 11 views
8

Ho problemi ad accedere a this.state in funzioni all'interno del mio componente. Ho già trovato this domanda su SO e aggiunto il codice suggerito al mio costruttore:React: "this.state" non è definito all'interno di una funzione componente

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

    ... 
    ... 

E ancora non funziona. this.state.currentRound non è definito. Qual è il problema?

+0

non posso davvero dire che cosa sta succedendo da questo, sembra a posto. Puoi caricare questo in un js fiddle? – JordanHendrix

+0

Non so come farlo con codice di reazione. – hellogoodnight

+0

base fiddle per es6 e reagire: https://jsfiddle.net/jhonvolkd/nrd015dm/ – JordanHendrix

risposta

5

Mi sono inventato qualcosa che ha funzionato. Ho cambiato il codice per il legame getCardsForRound nel costruttore a:

this.getCardsForRound = this.getCardsForRound.bind(this, this.state.currentRound); 
+0

You mi hai appena salvato. Ben fatto, grazie. – thatgibbyguy

0

Scrivi le funzioni in questo modo:

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

l'associazione per la parola chiave è lo stesso esterno e all'interno della funzione freccia grossa. Questo è diverso dalle funzioni dichiarate con la funzione, che può associare questo a un altro oggetto dopo l'invocazione. Mantenere questa associazione è molto utile per operazioni come la mappatura: this.items.map (x => this.doSomethingWith (x)).

Problemi correlati