Реакция setState не обновляется правильно - PullRequest
0 голосов
/ 14 января 2019

Я работаю над приложением Income / Expense, которое позволяет пользователю вводить данные и выбирать тип INC / EXP из выпадающего списка.

Проблема, с которой я сталкиваюсь, заключается в том, что мой Общий доход (после того, как я решу эту проблему), общая сумма обновления обновляется на 1 шаг назад, а мой Item_Percentage на 2 шага позади.

Пример ввода: Desc: Item 1 Amt: 500 Категория: INC-Earned Вывод: заработано 500 заработанных PCT: 100%

Input2: Item 2 Amt: 250 Категория: INC-sales Результат 2: Общий заработанный 500 заработанных PCT: 67% Всего продаж 250 Sales-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 голосов
/ 14 января 2019

Ознакомьтесь с документами . Обновления состояния асинхронные . Убедитесь, что вы учли это с помощью обратного вызова с 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

    })
}
...