React.JS在状态中使用两个值

Ale*_*mec 1 javascript reactjs

我正在尝试从两个输入进行数学运算。首先更新状态,然后使用新更新的状态添加两个值。

<input type="number" onChange={this.handleIncomeChange.bind(this)} value={this.state.income} />
Run Code Online (Sandbox Code Playgroud)

该代码不起作用:(结果总是后面有一个数字)

handleIncomeChange(e) {
    this.setState({income: e.target.value});
    this.state.resultMonth = +this.state.income - +this.state.expense;
}
Run Code Online (Sandbox Code Playgroud)

此代码有效:

handleIncomeChange(e) {
    const income = e.target.value;
    this.state.resultMonth = +income - +this.state.expense;
    this.setState({income: e.target.value});
}
Run Code Online (Sandbox Code Playgroud)

不知道我是否正确理解React.JS状态的概念。绝对不明白为什么第一个代码不起作用。

ctr*_*usb 5

您不应该直接使用修改状态this.state =(状态初始化期间除外)。使用setStateAPI 进行所有状态修改。

例如:

handleIncomeChange(e) {
  const newIncome = e.target.value;
  this.setState({
    income: newIncome,
    resultMonth: newIncome - this.state.expense
  });
}
Run Code Online (Sandbox Code Playgroud)

更新:基于代币和OP在以下评论中描述的问题。

您可以执行以下操作来解决可重用性问题。

handleDataChange(income, expense) {
  this.setState({
    income: income,
    expense: expense,
    resultMonth: income - expense
  });
}

handleIncomeChange(e) {
  const newIncome = e.target.value;
  this.handleDataChange(newIncome, this.state.expense);
}

handleExpenseChange(e) {
  const newExpense = e.target.value;
  this.handleDataChange(this.state.income, newExpense);
}
Run Code Online (Sandbox Code Playgroud)