简体   繁体   中英

How to fix 'Cannot read property 'value1' of undefined?

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'.

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
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM