I'm trying to do math operation from two inputs. First update state and then add two values with newly updated state.
<input type="number" onChange={this.handleIneChange.bind(this)} value={this.state.ine} />
This code isn't working: (result is always one number behind)
handleIneChange(e) {
this.setState({ine: e.target.value});
this.state.resultMonth = +this.state.ine - +this.state.expense;
}
This code is working:
handleIneChange(e) {
const ine = e.target.value;
this.state.resultMonth = +ine - +this.state.expense;
this.setState({ine: e.target.value});
}
Not sure if I understand concept of React.JS state correctly. Definitely don't understand why first code don't work.
I'm trying to do math operation from two inputs. First update state and then add two values with newly updated state.
<input type="number" onChange={this.handleIneChange.bind(this)} value={this.state.ine} />
This code isn't working: (result is always one number behind)
handleIneChange(e) {
this.setState({ine: e.target.value});
this.state.resultMonth = +this.state.ine - +this.state.expense;
}
This code is working:
handleIneChange(e) {
const ine = e.target.value;
this.state.resultMonth = +ine - +this.state.expense;
this.setState({ine: e.target.value});
}
Not sure if I understand concept of React.JS state correctly. Definitely don't understand why first code don't work.
Share Improve this question asked Jun 15, 2016 at 6:17 Aleš ChromecAleš Chromec 2551 gold badge4 silver badges9 bronze badges1 Answer
Reset to default 6You shouldn't modify the state directly using this.state =
(except during state initialisation). Make all your state modifications using the setState
API.
For example:
handleIneChange(e) {
const newIne = e.target.value;
this.setState({
ine: newIne,
resultMonth: newIne - this.state.expense
});
}
Update: based on the codepen and problem described by OP in ments below.
You could do something like the following to solve the issue of reusability.
handleDataChange(ine, expense) {
this.setState({
ine: ine,
expense: expense,
resultMonth: ine - expense
});
}
handleIneChange(e) {
const newIne = e.target.value;
this.handleDataChange(newIne, this.state.expense);
}
handleExpenseChange(e) {
const newExpense = e.target.value;
this.handleDataChange(this.state.ine, newExpense);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745608929a4635834.html
评论列表(0条)