2

I have the React component below and I want to access this.state.board (a 2D array with 0 or 1 for each element) from a function randomPosition(). When I call randomPosition it returns "cannot read property state of undefined". Am I doing something wrong with the this keyword?

var App = React.createClass({

getInitialState(){

  return {

   board: []

}

},

randomPosition: function(){
//generates a random position on this.state.board array

  var position = [];
  var positionX = null;
  var positionY = null;

  var generatePosition = function(){

    positionX = Math.floor(Math.random() * 64);
    positionY = Math.floor(Math.random() * 64);

    if(this.state.board[positionX][positionY] === 1){

      position.push(positionX, positionY);
      return position;

    } else {

      generatePosition();

    }

  }

  generatePosition();

}


})

thanks for the help!

chemook78
  • 1,058
  • 3
  • 12
  • 35

1 Answers1

1

Your generatePosition function will have its own scope and hence this inside this function will point to its own scope rather than the outer scope where state is accessible. You can store the reference of the outer scope and then use that inside this function like

randomPosition: function(){
//generates a random position on this.state.board array

  var position = [];
  var positionX = null;
  var positionY = null;
  var that = this;
  var generatePosition = function(){

    positionX = Math.floor(Math.random() * 64);
    positionY = Math.floor(Math.random() * 64);

    if(that.state.board[positionX][positionY] === 1){

      position.push(positionX, positionY);
      return position;

    } else {

      generatePosition();

    }

  }
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318