【问题标题】:Display to two decimal places - React.Js显示到小数点后两位 - React.Js
【发布时间】:2020-03-08 06:39:50
【问题描述】:

我正在尝试将计算结果显示到小数点后两位。我创建的函数具有从对象获取属性(“金额”属性)的行为,并将其添加到起始余额(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 位。我更加困惑,因为我使用了控制台日志的输出到小数点后两位。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您看到多于两位小数的原因是您将transactionData 的每个元素的runningTotal 键设置为running,而没有调用toFixed。记录时您会看到所需的格式,因为您在记录时调用了toFixed

要解决此问题,我建议将 toFixedrunningTotal 计算中完全删除,并且仅在 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() {
    // ...
  }
};

【讨论】:

  • 我相信我在发布我的问题之前已经尝试过了。我收到以下错误:TypeError: Cannot read property 'toFixed' of null Transactions C:/Users/Daniel/projects/react-projects/checkbook-app/src/components/checking/transactions.js:9 6 | &lt;td&gt;{props.date} &lt;/td&gt; 7 | &lt;td&gt;{props.transaction}&lt;/td&gt; 8 | &lt;td&gt;{props.amount}&lt;/td&gt; &gt; 9 | &lt;td&gt;{props.runningTotal.toFixed(2)}&lt;/td&gt; | ^ 10 | &lt;/tr&gt; 11 | 12 | );
  • 这将在初始渲染时发生。我建议将runningTotal 的初始值从null 更改为0,或者将addRunningTotal 的调用移至构造方法并让它返回更新后的transactionData,而不是调用setState。跨度>
  • 成功!做到了。谢谢你。 “那个”是指我将初始值从 null 更改为 0。我是否正确假设一旦我将其连接到数据库,任何替换 runningTotal 或连接到 runningTotal 的东西也必须是整数?
  • 是的,因为toFixedNumber 类型的方法,所以nullString 没有toFixed 方法。
  • 那么,告诉我,在渲染时直接在前端使用它还是在将数据保存在数据库中时在后端使用它更好?哪种方法更好?
猜你喜欢
  • 2011-05-27
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
相关资源
最近更新 更多