在我的反应应用程序中,我收到API作为字符串的成本(如990.00)。我将它存储在具有排序功能的素材UI表中。要对成本进行排序,它应采用数字格式。我正在使用toFloat()将其转换为数字,但我只获得了900。如果我将它修改为toFloat()。toFixed(2),它将再次转换为字符串。如果我将它修改为toFloat()。round(2),则根本没有输出。var cost = '900.00'var numericCost = toFloat(cost) //type - number but no decimal zerosvar numericCost = toFloat(cost).toFixed(2) //type - string, so can't sort itvar numericCost = toFloat(cost).round(2) //no output (can't see the data)如何使用带有以下十进制零的类型 - 数字来获取该数字?这是排序方法:let counter = 0;function createData(projectId, projectName, projectStatus, totalCost, paymentStatus, clientName, email, phone) { counter += 1; return { id: counter, projectId, projectName, projectStatus, totalCost, paymentStatus, clientName, email, phone };}function desc(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0;}function getSorting(order, orderBy) { return order === 'desc' ? (a, b) => desc(a, b, orderBy) : (a, b) => -desc(a, b, orderBy);}class AllTable extends React.Component { constructor(props) { super(props); this.state = { order: 'asc', orderBy: 'userName', data: [], }; }componentDidMount() { API.get('url') .then(({ data }) => { this.setState({ data: data.response.map( job => ( createData( job.project_id, parseFloat(job.total), job.payment_status, ) ) ) }) }) .catch((err) => { console.log("AXIOS ERROR: ", err); }) }
3 回答

守着星空守着你
TA贡献1799条经验 获得超8个赞
您尝试解决的核心问题是按数字的某个版本(数值)进行排序,然后显示另一个(具有已定义精度的字符串)。解决方案是将这两个问题分开,这样您就不会使用相同的值来排序和显示:
render() {
let data = this.props.data.sort((a, b) => {
// This is the sorting function, so we need to treat the values as a number
return toFloat(a.cost) - toFloat(b.cost);
});
return data.map(n => {
// Now we're showing the data, so treat it as a string
// It's already a string fetched from the API in the format needed, so just use directly
return (
<TableRow key={n.id}>
<TableCell>{n.cost}</TableCell>
</TableRow>
);
});
}
添加回答
举报
0/150
提交
取消