簡體   English   中英

如何在ReactJS中對JSON數據進行排序

[英]How to sort JSON data in ReactJS

誰能幫我在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>
        )
    }

根據docsdata.sortcompareFunction需要返回一個整數。 比較數字時,您可以簡單地從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});

    });

@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的來源: 鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM