Reputation: 17
What I need is to print and save in a variable or in a state the value of globalValue, the sum of the two "numbers".
The proplem with this code is that what is printed in the , is not the real value, but is the penultimate. For example if I put on the Textfields 1 and 1 will show me 0, but if later I change them for a 3 and 3, it will show me 2 because of the 1 plus 1. I can't use a setState inside de "componentDidUpdate" for this reason I'm using a var, but I'm sure there should be a better way.
Thank you for your attention and I hope I can learn wit your answers!
var globalValue=0
class ExampleComponent extends Component{
constructor(){
super();
this.state=({
number1:0,
number1:0,
})
}
componentDidUpdate(){
globalValue=this.state.valu1+this.state.value2,
}
updateNumber1(evt){
this.setState({
value1: evt.target.value,
});
}
updateNumber2(evt){
this.setState({
value2: evt.target.value,
});
}
<Textfield value={this.state.number1} onChange={evt => this.updateNumber1(evt)}/>
<Textfield value={this.state.number2} onChange={evt => this.updateNumber2(evt)}/>
<h2>Global value is:{globalValue}</h2>
Upvotes: 0
Views: 46
Reputation: 229
Your code is missing a lot. A full working demo would be helpful. But the last 3 lines (I think is the render method) should be a pure function, which only access this.props and this.state as input. Not globalValue. The calculation should be there as well and not in componentDidUpdate. This method is for other side effects.
So just use
<h2>Global value is:{this.state.number1 + this.state.number2}</h2>
Upvotes: 2