如何在 ReactJS 中对 JSON 数据进行排序

msh*_*vas 1 javascript sorting json reactjs redux

任何人都可以帮我在 ReactJs 中对 json 数据进行排序吗?现在它对我来说不能正常工作。另外,如果我想按标题排序,它会一样吗?谢谢。

我正在尝试如下:

componentDidMount() 
{
        fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
            .then((data) => {
                data.sort(function (a, b) {
                    return a.userId> b.userId;
                })
                data.sort();
                this.setState({data: data});

            });

    }

    render() {
        return (
            <div>
                <br/><br/>
                <br/><br/>

                < table className="table">

                    <th>User Id</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Action</th>
                    <tbody>{this.state.data.map(function (item, key) {
                        return (
                            <tr key={key}>
                                <td>{item.userId}</td>
                                <td>{item.id}</td>
                                <td>{item.title}</td>
                                <td>{item.body}</td>
                            </tr>
                        )

                    })}</tbody>
                </table>

            </div>
        )
    }
Run Code Online (Sandbox Code Playgroud)

gai*_*zov 5

compareFunctiondata.sort需要返回一个整数,根据文档。比较数字时,您可以简单地ab数字中减去数字,在您的情况下,a.userId - b.userId.

此代码有效

fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
    .then((data) => {
        data.sort((a, b) => a.userId - b.userId);
        this.setState({data: data});

    });
Run Code Online (Sandbox Code Playgroud)