2016-09-21 19 views
5

Próbuję wywołać ShuffleCards podczas zdarzenia click w komponencie ReactJs. Jednak ja otrzymuję następujący błąd:React JS Uncaught Błąd odniesienia: funkcja nie zdefiniowana

Uncaught ReferenceError: shuffleCards is not defined 

Oto mój kod:

constructor(props) { 
    super(props); 

    this.state = { 
     count: 0 
    }; 
} 

shuffleCards(array) { 
    var i = array.length, 
     j = 0, 
     temp; 

    while (i--) { 
     j = Math.floor(Math.random() * (i+1)); 

     temp = array[i]; 
     array[i] = array[j]; 
     array[j] = temp; 
    } 
    return array; 
} 

handleClickEvent(event) { 
    var cards = [ 
     {txt: "A", 
     isDisplayed: false}, 
     {txt: "B", 
     isDisplayed: false}, 
     {txt: "C", 
     isDisplayed: false} 
    ]; 
    if (this.state.count == 0) { 
     cards = shuffleCards(cards); 
    } 

} 
+7

'this.shuffleCards' – zerkms

+0

@zerkms wow nie może uwierzyć, że zrobił myśleć robi. zadziałało. dzięki! – janeeyrea

Odpowiedz

0

będzie to praca dla Ciebie? Demo tutaj: http://codepen.io/PiotrBerebecki/pen/qaRdgX

Przegapiłeś this odnosząc się do shuffleCards w metodzie handleClickEvent.

shuffleCards(array) { 
    // logic here 
} 

handleClickEvent(event) { 
    cards = this.shuffleCards(cards); 
} 

render() { 
    return (
    <button onClick={this.handleClickEvent.bind(this)}>Click me</button> 
); 
} 
12

EDIT prostu zobaczyłem komentarze i że zerkms już ci z roztworu. Zostawię moją odpowiedź dla celów wyjaśnienia.


Twoim problemem jest to, że wewnątrz handleClickMethod, dzwonisz shuffleCards zamiast this.shuffleCards

shuffleCards(array) { 
    // ... 
} 

handleClickEvent(event) { 
    // ... 
    if (this.state.count == 0) { 
     cards = this.shuffleCards(cards); // here you should use `this.` 
    } 
} 

Powodem jest fakt shuffleCards metoda jest zdefiniowana na składnik, który jest dostępny z jego metod za pośrednictwem właściwości this .

Jeśli zdefiniowano shuffleCards w handleClickMethod, a następnie można nazwać bez dostępu this:

handleClickEvent(event) { 

    function shuffleCards(array) { 
     // ... 
    } 

    // ... 
    if (this.state.count == 0) { 
     cards = shuffleCards(cards); // here you don't need `this.` 
    } 
} 
Powiązane problemy