Reputation: 93
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'.
Upvotes: 1
Views: 175
Reputation: 3138
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
};
}
Upvotes: 3