1
constructor() {
  super();
  this.state = {
    value1 : Math.floor(Math.random() * 100),
    value2 : Math.floor(Math.random() * 100),
    value3 : Math.floor(Math.random() * 100),
    proposedAnswer : Math.floor(Math.random() * 3) + this.state.value1 + this.state.value2 + this.state.value3,
    numQuestions : 0,
    numCorrect : 0
  };
}

I don't understand how it cannot read the value of the variable 'value1'.

4
  • 1
    The state is empty at the very beginning, so you can't reference it that way. Try to extract value 1,2,3 as variables and use the variable instead of this.state Commented Jun 25, 2020 at 9:25
  • Its still not defined to be used Commented Jun 25, 2020 at 9:25
  • You are using variable inside it's declaration, that's why it's undefined Commented Jun 25, 2020 at 9:26
  • you accessed state.value1 before the assignment ends Commented Jun 25, 2020 at 9:31

1 Answer 1

3

The state is still empty when you want to use it.
When you call this.state.value1, it won't refer to the current object but to the state itself, which hasn't been set yet because you're defining it.

You could extract the values as local variables and use them instead.

constructor() {
  super();
  const val1 = Math.floor(Math.random() * 100)
  const val2 = Math.floor(Math.random() * 100)
  const val3 = Math.floor(Math.random() * 100)
  this.state = {
    value1 : val1,
    value2 : val2,
    value3 : val3,
    proposedAnswer : Math.floor(Math.random() * 3) + val1 + val2 + val3,
    numQuestions : 0,
    numCorrect : 0
  };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I see. Thank you very much.
@ABGR they are random values

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.