簡體   English   中英

顯示兩位小數 - React.Js

[英]Display to two decimal places - React.Js

我試圖將計算結果顯示為兩位小數。 我創建的函數具有從對象中獲取屬性(“amount”屬性)的行為,並將其添加到起始余額 (startBal) 或將其添加到之前的 runningTotal 屬性 (runnigTotal)。 完成此計算后,我希望結果顯示為兩位小數,因為這是我正在編寫的財務應用程序。

我正在嘗試使用 .toFixed() 方法,但實際上我沒有綁定這個方法,我只是想讓它工作。

這是我的主要組件。 相關函數是 addRunningTotal()

import React, { Component } from 'react';

import TransactionSearch from './transactionSearch.js';
import PendingTransactions from './pendingTransactions.js';
import Transactions from './transactions.js';

class CheckingAccount extends Component {
  state = {
    startBal: 1000,
    pendingTransData: [
      { id: 0, date: '1/1/2020', transaction: "gas", amount: -25.45 },
      { id: 1, date: '1/2/2020', transaction: "cell phone", amount: -127.35 },
      { id: 2, date: '1/3/2020', transaction: "car payment", amount: -303.97, },
    ],
    transactionData: [
      {
        id: 0,
        date: '1/1/2020',
        transaction: "gas",
        amount: -35.45,
        runningTotal: null
      },
      {
        id: 1,
        date: '1/2/2020',
        transaction: "cell phone",
        amount: -227.35,
        runningTotal: null
      },
      {
        id: 2,
        date: '1/3/2020',
        transaction: "car payment",
        amount: -403.97,
        runningTotal: null
      },
    ]
  }

  addRunningTotal() {
    let { transactionData, startBal } = this.state

    console.log('start Balance: ', startBal);
    let prevAmount, running;
    transactionData.map((el, i) => {
      if (i === 0) {
        running = el.runningTotal = el.amount + startBal;
        prevAmount = el.runningTotal;

        console.log(running.toFixed(2))
        return running.toFixed(2);
      } else if (i > 0) {
        running = el.runningTotal = prevAmount + el.amount;
        prevAmount = el.runningTotal;

        console.log(running.toFixed(2))
        return running.toFixed(2);
      }
    });
    console.log('out of map function')
    console.log(transactionData);

    this.setState({ transactionData: transactionData, startBal: startBal });
  };

  componentDidMount() {
    this.addRunningTotal()
  }

  render() {
    let pendTransData = (
      <div>
        <h1>PendingTransactions</h1>
        <table>
          <tr>
            <th>Date</th>
            <th>Transaction</th>
            <th>Amount</th>
          </tr>
        </table>
        {this.state.pendingTransData.map((pendingTransData, index) => {
          return <PendingTransactions
            key={pendingTransData.id}
            date={pendingTransData.date}
            transaction={pendingTransData.transaction}
            amount={pendingTransData.amount} />
        })}
      </div>
    );

    let transData = (
      <div>
        <h1>Transaction Component</h1>
        <table>
          <tr>
            <th>Date</th>
            <th>Transaction</th>
            <th>Amount</th>
            <th>Running Total</th>
          </tr>
        </table>
        {this.state.transactionData.map((transactionData, index) => {
          return <Transactions
            key={transactionData.id}
            date={transactionData.date}
            transaction={transactionData.transaction}
            amount={transactionData.amount}
            runningTotal={transactionData.runningTotal} />
        })}
      </div>
    );

    return (
      <div className="App" >
        <h1> Checking Account</h1>
        <TransactionSearch />
        {pendTransData}
        {transData}
      </div>
    );
  };
};

export default CheckingAccount;

這是我的子組件。

import React from 'react';

function Transactions(props) {
  return (
    <tr>
      <td>{props.date} </td>
      <td>{props.transaction}</td>
      <td>{props.amount}</td>
      <td>{props.runningTotal}</td>
    </tr>

  );
}

export default Transactions;

我希望看到運行總計列顯示到小數點后兩位,但由於某種原因,它顯示到小數點后大約 13 位。 我更加困惑,因為 console.log 的我已經使用輸出到小數點后兩位。

您看到兩位小數更多的原因是您設置的runningTotal的每個元素的關鍵transactionDatarunning ,而無需調用toFixed 您在登錄時會看到所需的格式,因為您在登錄時調用了toFixed

為了解決這個問題,我建議從runningTotal計算中完全刪除toFixed並且只在render方法中使用toFixed ,因為它應該只用於演示目的。

例子:

function Transactions(props) {
  return (
    <tr>
      <td>{props.date} </td>
      <td>{props.transaction}</td>
      <td>{props.amount}</td>
      <td>{props.runningTotal.toFixed(2)}</td>
    </tr>

  );
}

此外,我建議重構addRunningTotal方法,使其更清晰地閱讀並避免直接狀態操作。 例如:

addRunningTotal() {
  const { transactionData, startBal } = this.state;

  console.log('start Balance: ', startBal);
  let running = startBal;
  const transactionDataWithRunningTotals = transactionData.map(el => {
    running += el.amount;
    return {
      ...el,
      runningTotal: running,
    }
  });
  console.log('out of map function')
  console.log(transactionData);

  this.setState({ transactionData: transactionDataWithRunningTotals });
}

為了處理初始渲染中的問題,我會將您的組件更新為如下所示:

class CheckingAccount extends Component {
  constructor(props) {
    super(props);

    this.state = {
      startBal: 1000,
      pendingTransData: [
        { id: 0, date: '1/1/2020', transaction: "gas", amount: -25.45 },
        { id: 1, date: '1/2/2020', transaction: "cell phone", amount: -127.35 },
        { id: 2, date: '1/3/2020', transaction: "car payment", amount: -303.97, },
      ],
      transactionData: this.withRunningTotals([
        {
          id: 0,
          date: '1/1/2020',
          transaction: "gas",
          amount: -35.45,
          runningTotal: null
        },
        {
          id: 1,
          date: '1/2/2020',
          transaction: "cell phone",
          amount: -227.35,
          runningTotal: null
        },
        {
          id: 2,
          date: '1/3/2020',
          transaction: "car payment",
          amount: -403.97,
          runningTotal: null
        },
      ]),
    }
  }

  withRunningTotals() {
    const { transactionData, startBal } = this.state;

    let running = startBal;
    return transactionData.map(el => {
      running += el.amount;
      return {
        ...el,
        runningTotal: running,
      }
    });
  }

  render() {
    // ...
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM