反应setState无法正确更新

时间:2019-01-13 21:39:33

标签: reactjs components setstate

我正在开发一个收入/支出应用程序,该应用程序允许用户输入数据并从下拉列表中选择INC / EXP的类型。

我遇到的问题是我的总收入(一旦解决此问题,总费用即将到来)正在更新1步,而我的Item_Percentage落后2步。

示例输入:Desc:项目1 Amt:500 Categ:INC-Earned 产出:总收入500 PCT:100%

输入2:项目2修改:250类别:INC-销售 产出2:总收入500 PCT:67% 总销量250件,PCT:33%

   import React, { Component } from 'react';
   import IncomeList from './components/IncomeList';
   import ExpenseList from './components/ExpenseList';
   import AddItem from './components/AddItem';
   import Chart from './components/Chart';
   import './App.css';

   class App extends Component {
constructor(){
    super()
    this.state = {
        incomeItems: [],
        expenseItems: [],
        totalIncome: 0,
        totalExpense: 0,
        color: 'black',
        incEarned: 0,
        incInvest: 0,
        incSales: 0,
        incRe: 0,
        incServices: 0,
        incOther: 0,
        incEarnedPCT: 0,
        incInvestPCT: 0,
        incSalesPCT: 0,
        incRePCT: 0,
        incServicesPCT: 0,
        incOtherPCT: 0
    }
    this.addBudgetItem = this.addBudgetItem.bind(this); 
    this.addExpenseItem = this.addExpenseItem.bind(this);
    this.deleteIncomeItem = this.deleteIncomeItem.bind(this);
    this.deleteExpenseItem = this.deleteExpenseItem.bind(this);
}

addBudgetItem (item, amount, category) {
    let newIncomeTotal = this.state.totalIncome + parseInt(amount);
    this.setState({
        incomeItems: [...this.state.incomeItems, {item: item, amount: amount, category: category}],
        totalIncome: newIncomeTotal
    })
    const newIncList = this.state.incomeItems;
    let incEarned = this.state.incEarned;
    let incInvest = this.state.incInvest;
    let incSales = this.state.incSales;
    let incRe = this.state.incRe;
    let incServices = this.state.incServices;
    let incOther = this.state.incOther;

    let incEarnedPCT = 0;
    let incInvestPCT = 0;
    let incSalesPCT = 0;
    let incRePCT = 0;
    let incServicesPCT = 0;
    let incOtherPCT = 0;

    newIncList.map((item) => {
        if(item.category === 'earned'){
            incEarned += parseInt(item.amount);
            incEarnedPCT = incEarned/parseInt(this.state.totalIncome);
        } else if (item.category === 'invest'){
            incInvest += parseInt(item.amount);
            incInvestPCT = incInvest/parseInt(this.state.totalIncome);
        } else if (item.category === 'sales'){
            incSales += parseInt(item.amount);
            incSalesPCT = incSales/parseInt(this.state.totalIncome);
        } else if (item.category === 're'){
            incRe += parseInt(item.amount);
            incRePCT = incRe/parseInt(this.state.totalIncome);
        } else if (item.category === 'services'){
            incServices += parseInt(item.amount);
            incServicesPCT = incServices/parseInt(this.state.totalIncome);
        } else {
            incOther += parseInt(item.amount);
            incOtherPCT = incOther/parseInt(this.state.totalIncome);
        }
        this.setState({
            incEarnedPCT: incEarnedPCT,
            incInvestPCT: incInvestPCT,
            incSalesPCT: incSalesPCT,
            incRePCT: incRePCT,
            incServicesPCT: incServicesPCT,
            incOtherPCT: incOtherPCT
        })
    })
    console.log(`Earned: ${incEarned}  PCT: ${this.state.incEarnedPCT}\n Invest: ${incInvest} PCT: ${this.state.incInvestPCT}\n Sales: ${incSales} PCT: ${this.state.incSalesPCT}\n Real Estate: ${incRe} PCT: ${this.state.incRePCT}\n Services: ${incServices} PCT: ${this.state.incServicesPCT}\n Other: ${incOther} PCT: ${this.state.incOtherPCT}`);

    }


     render() {

return (
  <div className="App">
    <header className="App-header">
      <h1 className="App-title">Monthly Budget</h1>
    </header>

    <div className="container">
        <AddItem addBudgetItem={this.addBudgetItem} addExpenseItem={this.addExpenseItem}/>
        <div className="line"></div>
        <div className="UIdiv"> 
            <table>
                <h1>INCOME ITEMS</h1>
                <tr><IncomeList incomeList={this.state.incomeItems} deleteIncomeItem={this.deleteIncomeItem}/></tr>
                <p className="income-desc">Total Income: {this.state.totalIncome}</p>
            </table>
            <table>
                <h1>EXPENSE ITEMS</h1>
                <tr><ExpenseList expenseList={this.state.expenseItems} deleteExpenseItem={this.deleteExpenseItem}/></tr>
                <p className="expense-desc">Total Expense: {this.state.totalExpense} </p>
            </table>

    <h2 style={(this.state.totalIncome - this.state.totalExpense === 0) ? {color: 'black'}: (this.state.totalIncome > this.state.totalExpense) ? {color:'green'}:{color:'red'}}> TOTAL BALANCE: {this.state.totalIncome - this.state.totalExpense}</h2>
        </div>
    </div>
    <div>
    <Chart />
    </div>
 </div>
);
     }
  }

     export default App;

1 个答案:

答案 0 :(得分:2)

Check out the docs。状态更新是异步。如果以后的代码行将依赖新状态,请确保使用setState回调来解决这个问题。

this.setState的签名为this.setState(update, callback),因此您可以这样编写代码:

addBudgetItem (item, amount, category) {
  let newIncomeTotal = this.state.totalIncome + parseInt(amount);
    this.setState({
      incomeItems: [...this.state.incomeItems, {item: item, amount: amount, category: category}],
      totalIncome: newIncomeTotal
    }, () => {

      // Later lines of code should go here

    })
}