Reputation: 89
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.
Upvotes: 0
Views: 80
Reputation: 562
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
};
}
Upvotes: 1
Reputation: 976
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;
}
Upvotes: 1