数字是否需要是字符串以避免精度错误?



我正在尝试制作一个eth dapp,我正在使用react来创建前端。此错误来自前端端。这是我的错误,我得到了其中的 2 个都说同样的事情错误:

请将数字作为字符串或 BN 对象传递以避免精度错误

我尝试将 toString(( 放在 tokenBalance 和 ethBalance 的末尾,但我只是得到错误:

无法读取未定义的属性"toString"

这是我的代码:

import React, {Component} from 'react';
import tokenLogo from '../token-logo.png'
import ethLogo from '../eth-logo.png'

class Main extends Component{
constructor(props) {
super(props)
this.state = {
output: '0'
}
}
render(){
return (
<div id="content">
<div className="card mb-4" >
<div className="card-body">
<form className="mb-3" onSubmit={(event) => {
event.preventDefault()
let etherAmount
etherAmount = this.input.value.toString()
etherAmount = window.web3.utils.toWei(etherAmount, 'Ether')
this.props.buyTokens(etherAmount)
}}>
<div>
<label className="float-left"><b>Input</b></label>
<span className="float-right text-muted">
Balance: {window.web3.utils.fromWei(this.props.ethBalance.toString(), 'Ether')}
</span>
</div>
<div className="input-group mb-4">
<input
type="text"
onChange={(event) => {
const etherAmount = this.input.value.toString()
this.setState({
output: etherAmount * 100
})
}}
ref={(input) => { this.input = input }}
className="form-control form-control-lg"
placeholder="0"
required />
<div className="input-group-append">
<div className="input-group-text">
<img src={ethLogo} height='32' alt=""/>
&nbsp;&nbsp;&nbsp; ETH
</div>
</div>
</div>
<div>
<label className="float-left"><b>Output</b></label>
<span className="float-right text-muted">
Balance: {window.web3.utils.fromWei(this.props.tokenBalance, 'Ether')}
</span>
</div>
<div className="input-group mb-2">
<input
type="text"
className="form-control form-control-lg"
placeholder="0"
value={this.state.output}
disabled
/>
<div className="input-group-append">
<div className="input-group-text">
<img src={tokenLogo} height='32' alt=""/>
&nbsp; DApp
</div>
</div>
</div>
<div className="mb-5">
<span className="float-left text-muted">Exchange Rate</span>
<span className="float-right text-muted">1 ETH = 100 DApp</span>
</div>
<button type="submit" className="btn btn-primary btn-block btn-lg">SWAP!</button>
</form>
</div>
</div>
</div>
);
}
}
export default Main;

听起来你需要测试你的 prop 是否有值,然后再尝试使用它toString方法。像这样:

<span className="float-right text-muted">
Balance: {this.props.ethBalance ? window.web3.utils.fromWei(this.props.ethBalance.toString(), 'Ether') : ''}
</span>

最新更新