[英]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>
)
}
根据docs , 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});
});
@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.