我使用axios进行API查询,并使用NumberFromat更改十进制数字。这是App.js:
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import web3 from "./web3";
import NumberFormat from 'react-number-format';
export default class PersonList extends React.Component {
state = {
balance: '',
bn: '',
persons: []
};
async componentDidMount() {
const balance = await web3.eth.getBalance("0x2f6aA9e80385316eEe006AB8bB7943abF333A063") / 1e18;
const bn = financial(balance);
const axios = require('axios');
function financial(x) {
return Number.parseFloat(x).toFixed(2);
};
axios.get(`https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
this.setState({ balance, bn });
};
render() {
return (
<div>
<p>
{this.state.persons.map(person => <p>"portfolioValue": {this.state.bn}, "usdeth": {person.price_usd}</p>)}
</p>
</div>
);
}
}
显示为
“ portfolioValue”:0.06,“ usdeth”:93.270616772
因此,我需要更改第二个值的小数位数,例如93.27。看起来很容易,但是我坚持了下去。
答案 0 :(得分:0)
您应该使用下面提到的代码。
render() {
return (
<div>
<p>
{this.state.persons.map(person =>
<p>"portfolioValue": {this.state.bn}, "usdeth": {this.financial(person.price_usd)}</p>)
}
</p>
</div>
);
}
答案 1 :(得分:0)
您遇到了一些问题:
require('axios')
放在顶部文件中,而不要放在componentDidMount
中,这样可以提高性能。 编辑:您已经导入,因此不需要再次输入 financial
应该是一个实用程序,这意味着它很有用,应该在类中声明,而不是在函数componentDidMount
中声明。person.price_usd
,您没有使用financial
,所以它不起作用。这是解决方案
import React from 'react';
import './App.css';
import axios from 'axios';
import web3 from "./web3";
// useless library
// import NumberFormat from 'react-number-format';
// Require Axios here for better performance
// const axios = require('axios');
export default class PersonList extends React.Component {
state = {
balance: '',
bn: '',
persons: []
};
// place here for best utilities
financial = (x) => Number.parseFloat(x).toFixed(2);
async componentDidMount() {
const balance = await web3.eth.getBalance("0x2f6aA9e80385316eEe006AB8bB7943abF333A063") / 1e18;
const bn = this.financial(balance);
axios.get(`https://api.coinmarketcap.com/v1/ticker/ethereum/?convert=USD`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
this.setState({ balance, bn });
};
render() {
return (
<div>
<p>
{this.state.persons.map(person =>
<p>"portfolioValue": {this.state.bn}, "usdeth": {this.financial(person.price_usd)}</p>)
}
</p>
</div>
);
}
}