React JS Notc Reference Reference: function not defined

I try to call shuffleCards when the click event in the ReactJs component. However, I get the following error:

Uncaught ReferenceError: shuffleCards is not defined 

Here is my code:

 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); } } 
+11
source share
3 answers

EDIT Just saw the comments and that zerkms has already provided you with a solution. I will leave my answer for clarification.


Your problem is that inside handleClickMethod you are calling shuffleCards instead of this.shuffleCards
 shuffleCards(array) { // ... } handleClickEvent(event) { // ... if (this.state.count == 0) { cards = this.shuffleCards(cards); // here you should use `this.` } } 

The reason is that the shuffleCards method shuffleCards defined on your component, which is accessible from its methods using the this property.

If you defined shuffleCards in handleClickMethod , you can call it without access to this :

 handleClickEvent(event) { function shuffleCards(array) { // ... } // ... if (this.state.count == 0) { cards = shuffleCards(cards); // here you don't need `this.` } } 
+26
source

Will this work for you? Demo here: http://codepen.io/PiotrBerebecki/pen/qaRdgX

You missed this when accessing shuffleCards in the handleClickEvent method.

 shuffleCards(array) { // logic here } handleClickEvent(event) { cards = this.shuffleCards(cards); } render() { return ( <button onClick={this.handleClickEvent.bind(this)}>Click me</button> ); } 
+2
source

I had the same problem.

And I am updating the " response-scripts " and fixing this problem.

Probably fix it.

 npm i react-scripts 
0
source

All Articles