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

3

请问有人能帮我在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>
        )
    }

第二次调用data.sort()(没有自定义排序函数逻辑)会覆盖初始的排序逻辑,这就是为什么你自定义的比较逻辑a.userID > b.userId没有达到预期结果的原因。@gaiazov在下面的答案中提到了按标题排序的问题,使用a.title - b.title可以解决。 - Tobiah Rex
感谢解释。非常感激。 - mshrivas
2个回答

7
data.sort 中,compareFunction 需要返回一个整数,根据文档。当比较数字时,您可以简单地用 b 数减去 a 数,例如 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});

    });

3
@mshrivas,请测试以下按标题排序的代码:
componentDidMount()
{
  fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
    .then((data) => {
      data.sort((a,b) => a.title.localeCompare(b.title));
      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>
  )
}

localeCompare的来源:链接


这个链接是一个关于如何使用JavaScript按键对对象数组进行字母顺序排序的文章。我在实践中尝试过,这种方法对我很有效。 - vinny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接