javascript - React.JS working with two values in state - Stack Overflow

I'm trying to do math operation from two inputs. First update state and then add two values with n

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

You 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

相关推荐

  • javascript - React.JS working with two values in state - Stack Overflow

    I'm trying to do math operation from two inputs. First update state and then add two values with n

    11小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信