2016-09-21 131 views
5

我試圖在ReactJs組件中的單擊事件時調用shuffleCards。不過,我收到以下錯誤:React JS未捕獲參考錯誤:未定義函數

Uncaught ReferenceError: shuffleCards is not defined 

這裏是我的代碼:

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哇不能相信我沒有想到這樣做。有效。謝謝! – janeeyrea

回答

0

將這項工作嗎?這裏演示:http://codepen.io/PiotrBerebecki/pen/qaRdgX

您在handleClickEvent方法參照shuffleCards時沒有this

shuffleCards(array) { 
    // logic here 
} 

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

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

編輯剛纔看到的意見和zerkms已經與提供的解決方案你。爲了澄清目的,我會留下我的回答。


你的問題是 handleClickMethod裏面,你在呼喚 shuffleCards代替 this.shuffleCards

shuffleCards(array) { 
    // ... 
} 

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

,就是因爲shuffleCards方法您的組件,它是經由this屬性它的方法訪問定義。

如果您在handleClickMethod中定義shuffleCards,那麼你可以把它無需訪問this

handleClickEvent(event) { 

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

    // ... 
    if (this.state.count == 0) { 
     cards = shuffleCards(cards); // here you don't need `this.` 
    } 
} 
相關問題