最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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);
}
发布评论

评论列表(0)

  1. 暂无评论