2016-05-11 8 views
8

コンポーネント内の関数でthis.stateにアクセスする際に問題があります。私はすでにSO上this質問を発見し、私のコンストラクタに提案されたコードを追加しました:それはまだ動作しませんReact: 'this.state'はコンポーネント関数内では定義されていません

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

    ... 
    ... 

this.state.currentRoundは未定義です。何が問題ですか?

+0

本当にこのことから何が起こっているのかわからないので、うまく見えます。これをjsのフィドルにアップロードできますか? – JordanHendrix

+0

私は反応コードでそれを行う方法を知らない。 – hellogoodnight

+0

es6と反応するためのベースフィドル:https://jsfiddle.net/jhonvolkd/nrd015dm/ – JordanHendrix

答えて

5

私はうまくいきました。この方法あなたの関数を書く

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

ちょうど私を救った。さて、ありがとう。 – thatgibbyguy

0

:私はにコンストラクタでgetCardsForRoundを結合するためのコードを変更し

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

が、これは同じ外であるキーワードに対して結合し、太い矢印の機能の中で。これは、functionで宣言された関数とは異なります。これは、呼び出し時にこれを別のオブジェクトにバインドできます。このバインディングのメンテナンスは、マッピングなどの操作にとって非常に便利です:this.items.map(x => this.doSomethingWith(x))。

関連する問題