0

When I am trying to declare a state variable based on other state it is not working whatever I try. Is it forbidden by react itself or am I doing something wrong?

Basically I am trying to achieve something like:

class App extends Component {
state={
  a:123,
  b:234,
  c:this.state.a+this.state.b
}



render() {
return (
  <div className="App">
    {this.state.c}
  </div>
);
}
}

FYI: I am not trying to do something like calculating c in curly brackets like: {this.state.a+this.state.b} but rather interested in how it works inside the state.

Thanks for help!

Dimitry Ivashchuk
  • 635
  • 2
  • 7
  • 23

1 Answers1

0

Well the issue here is simple, the declaration statement of your state hasn't finished when you try to do this.state.a + this.state.b. The statement will finish after the } - Only then can you access those variables.

Instead you could do:

state={
  a:123,
  b:234,
}
this.state.c = this.state.a + this.state.b
Chris
  • 57,622
  • 19
  • 111
  • 137
  • 1
    Thanks, I think I’ve got the point! But then the question is, would it be something appropriate to do in react while it sets state outside of state object and not through setState method? – Dimitry Ivashchuk Jun 15 '18 at 21:17