React JS Uncaught Reference Error:函数未定义

时间:2016-09-21 22:59:34

标签: javascript reactjs

我试图在ReactJs组件中点击事件时调用shuffleCards。但是,我收到以下错误:

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);
    }

}

3 个答案:

答案 0 :(得分:24)

编辑刚看到评论, 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属性从其方法访问。

如果您在shuffleCards中定义了handleClickMethod,那么您可以在不访问this的情况下调用它:

handleClickEvent(event) {

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

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

答案 1 :(得分:1)

这对你有用吗?在这里演示:http://codepen.io/PiotrBerebecki/pen/qaRdgX

"2"方法中引用this时,您错过了shuffleCards

handleClickEvent

答案 2 :(得分:0)

我遇到了同样的问题。

然后我升级“ 反应脚本”并解决此问题。

可能会解决此问题。

npm i react-scripts