ReactJS:如何使用 toFixed(2) 修复数字行值长度

and*_*mit 2 javascript tofixed reactjs fetch-api

我将从 API 获取的数据打印到表中,但将行数值固定为小数时遇到一些困难。如果 API 中的行数据由数值组成,即 等10.0, 333, 8 or 100,则最终以十进制值呈现 -> 10.00, 333.00, 100.00

我熟悉的函数.toFixed(2)在 React 中的运行方式与我以前在 javaScript 中编写它的方式不同。我认为我误导了 ES6 标准,但我不确定。如果我避免使用.toFixed(2).

在此输入图像描述

这是我的代码示例rows.toFixed(2),但它的功能不佳:

class App extends React.Component
{
    constructor()
    {
        super();
        this.state = {
            rows: [],
            columns: []
        }
    }

    componentDidMount()
    {

        fetch( "http://ickata.net/sag/api/staff/bonuses/" )
            .then( function ( response )
            {
                return response.json();
            } )
            .then( data =>
            {
                this.setState( { rows: data.rows, columns: data.columns } );
            } );

    }

    render()
    {

        return (
            <div id="container" className="container">
                <h1>Final Table with React JS</h1>
                <table className="datagrid">
                    <thead>
                        <tr> {
                            this.state.columns.map(( column, index ) =>
                            {
                                return ( <th>{column}</th> )
                            }
                            )
                        }
                        </tr>
                    </thead>
                    <tbody> {
                        this.state.rows.toFixed(2).map( row => (
                            <tr>{row.toFixed(2).map( cell => (
                                <td>{cell}</td>
                            ) )}
                            </tr>
                        ) )
                    }
                    </tbody>
                </table>
            </div>
        )
    }
}


ReactDOM.render( <div id="container"><App /></div>, document.querySelector( 'body' ) );
Run Code Online (Sandbox Code Playgroud)

欢迎您直接为我的 Repo 做出贡献:Fetching API data into a table

.toFixed下面是我的示例,使用后的样子:

在此输入图像描述

不幸的是我无法在ReactJs.org找到相关文档

它不起作用rows[].length.toFixed(2)

任何建议将不胜感激!

Dun*_*ker 6

你被toFixed(2)再次调用this.state.rows,它是一个数组 - 这可能会抛出一个错误,导致渲染失败。这解释了为什么您在屏幕上看不到任何内容。

我怀疑你想要更多这样的东西:

this.state.rows.map( row => (
<tr>{row.map( cell => (
<td>{typeof cell === 'number' ? cell.toFixed( 2 ) : cell}</td>
) )}
</tr>
) )
Run Code Online (Sandbox Code Playgroud)

在此版本中,我们查看每个单元格 - 如果内容是数字,我们toFixed(2)在渲染之前调用它 - 否则我们只渲染它。从技术上讲,这个答案是正确的,但它也打印年龄行值,该值不应该是小数。我想我必须对 rows[3] 值进行硬编码。