0
votes

I want to access state's property when state isn't mounted yet.

class App extends React.Component{
    constructor(props){
    super(props)
    this.state = {
       test: 2,
       score: test * 2
    }
}

I wanna make score 4 but get this error:

'test' is not defined no-undef

P.S score: this.state.test doesn't work neither.

2

2 Answers

1
votes

You are in the constructor, so you can update your state without .setState() and without consequence, like that:

constructor(props) {
  super(props);
  this.state = {
    test: 2,
  };
  this.state.score = this.state.test * 2;
}
1
votes

One way to do it would be to define the variable before setting the state and then use it:

constructor(props) {
  super(props);
  const test = 2;
  this.state = {
    test,
    score: test * 2
  };
}