2016-05-11 17 views
8

के अंदर अपरिभाषित है मुझे अपने घटक के अंदर कार्यों में this.state तक पहुंचने में समस्या हो रही है। मैं पहले से ही इतने पर this सवाल पाया और मेरे निर्माता करने का सुझाव दिया कोड कहा:प्रतिक्रिया: '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

वास्तव में यह नहीं बता सकता कि इससे क्या चल रहा है, यह ठीक दिखता है। क्या आप इसे जेएस फीड में अपलोड कर सकते हैं? – JordanHendrix

+0

मुझे नहीं पता कि प्रतिक्रिया कोड के साथ ऐसा कैसे करें। – hellogoodnight

+0

एएस 6 के लिए आधार पहेली और प्रतिक्रिया: 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

कीवर्ड के लिए बाध्यकारी यह है एक ही बाहर और वसा तीर समारोह के अंदर। यह फ़ंक्शन के साथ घोषित कार्यों से अलग है, जो इसे आमंत्रण पर किसी अन्य ऑब्जेक्ट से जोड़ सकता है। इस बाध्यकारी को बनाए रखना मैपिंग जैसे संचालन के लिए बहुत सुविधाजनक है: this.items.map (x => this.do SomethingWith (x))।

संबंधित मुद्दे