簡體   English   中英

React:組件函數內部未定義'this.state'

[英]React: 'this.state' is undefined inside a component function

我在組件內部的函數中訪問this.state遇到麻煩。 我已經在SO上找到了這個問題,並向我的構造函數添加了建議的代碼:

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是未定義的。 問題是什么?

我想出了一些有效的方法。 我將構造函數中用於綁定getCardsForRound的代碼更改為:

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

這樣編寫函數:

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綁定對於諸如映射這樣的操作非常方便:this.items.map(x => this.doSomethingWith(x))。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM