Hasnain
Hasnain

Reputation: 41

Accessing the state varriable

I am unable to access my state variable in the App class. Can anybody Recommend me some solution?

class App extends React.Component {
  constructor(props) {
    super(props);

    var question1 = [
      "What is 8*1",
      "What is 8*2",
      "What is 8*3",
      "What is 8*4"
    ];
    var choice = ["1", "2", "4", "8", "9"];
    this.state = {
      question1: this.question1,
      choice: this.choice,
      correct: 0,
      incorrect: 0
    };
    console.log(this.state.choice);
    this.clickHandler = this.clickHandler.bind(this);
  }
  clickHandler() {
    console.log("hello world");
  }
  render() {
    return (
      <div>
        <Question question={this.state.question1} choice={this.state.choice} />
      </div>
    );
  }
}

Upvotes: 2

Views: 44

Answers (1)

Mechanic
Mechanic

Reputation: 5380

remove this in this.question1 and this.choice and always prefer let/const over var;

constructor(props) {
    super(props);

    const question1 = [
      "What is 8*1",
      "What is 8*2",
      "What is 8*3",
      "What is 8*4"
    ];
    const choice = ["1", "2", "4", "8", "9"];
    this.state = {
      question1: question1,
      choice: choice,
      correct: 0,
      incorrect: 0
    };
    this.clickHandler = this.clickHandler.bind(this);
  }

Upvotes: 4

Related Questions