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

时间:2018-01-28 23:41:26

标签: javascript json reactjs sorting 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>
        )
    }

2 个答案:

答案 0 :(得分:3)

根据docscompareFunction中的data.sort需要返回一个整数。比较数字时,您可以简单地从a数字中减去b个数字,在您的情况下,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});

    });

答案 1 :(得分:0)

@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的来源:link