javascript - 如何按升序和降序对列进行排序?
问题描述
我是使用对象数组创建的表,现在我不明白我们如何通过单击reactjs 中的列名按升序和降序对表进行排序。我在stackoverflow上尝试了很多概念,但它似乎对这个没有用。这是一个非常愚蠢的问题,但我已经停止了很多天。
class Hello extends Component {
constructor(props) {
super(props)
this.state = {
search: '',
Data:[
{
id: 1,
fullName: 'abc',
email:'example@gmail.com',
},
{
id: 2,
fullName: 'qps',
email:'qps@gmail.com',
},
{
id: 3,
fullName: 'qwe',
email:'qwe@gmail.com',
},
]
}
}
function Sort(){
//what need to write here;
}
render() {
return (
<div>
<h1>welcome to React</h1>
<table className="table table-hover table-dark">
<tbody>
<tr>
<th onChange={this.Sort.bind(this)}>ID</th>
<th>Full Name</th>
<th>Email</th>
</tr>
{
this.state.Data.map((item,index)=>(
<tr key={item.id}>
<td >{item.id}</td>
<td >{item.fullName}</td>
<td>{item.email}</td>
</tr>
))
}
</tbody>
</table>
</div>
)
}
}
export default Hello
解决方案
- 您需要将
onChange
处理程序切换到onClick
. - 添加一些状态来存储最后的排序方向;
- 使用 Array
sort()
方法,但注意不要改变你的状态。
this.state = {
order: 'ASC'
...
function sort() {
let sortedList = [...this.state.Data];
let newOrder = this.state.order === 'ASC' ? 'DESC' : 'ASC';
if (newOrder === 'ASC') {
sortedList.sort((a, b) => a.id - b.id)
} else {
sortedList.sort((a, b) => b.id - a.id)
}
this.setState({ Data: sortedList, order: newOrder });
}
为了能够对任何列进行排序,我将进行以下更改:
function sort(column) {
const sortedList = [...this.state.Data];
const newOrder = this.state.order === "ASC" ? "DESC" : "ASC";
const sortValue = (v1, v2) => {
if (column === 'id') return v1.id - v2.id;
return (v1[column] ?? '')
.toLowerCase()
.localeCompare((v2[column] ?? '').toLowerCase())
}
if (newOrder === "ASC") {
sortedList.sort((a, b) => sortValue(a, b));
} else {
sortedList.sort((a, b) => sortValue(b, a));
}
this.setState({ Data: sortedList, order: newOrder });
}
onClick
并为每个列标题添加适当的处理程序。
<th onClick={() => this.sort('id')}>ID</th>
<th onClick={() => this.sort('fullName')}>Full Name</th>
<th onClick={() => this.sort('email')}>Email</th>
推荐阅读
- php - 在联系表 7 字段中使用 URL 参数
- javascript - Sequelize - 在 findAll 之后,使用单个查询删除
- c# - gRPC - 在 c# 中没有死锁的许多客户端的过程
- java - 如何在 JLabel 中打印堆栈?
- php - 在现有的 3 点/更多图标下添加了 SilverStripe 自定义网格字段操作按钮
- python - 我在 cmd 上遇到了 django runserver 命令的问题
- awk - 使用变量和字边界的 awk 匹配列
- firebase - 我们正在使用带有 react-native 的 firebase,而 firebase 正在使用 crashlytics(我猜)。我们遇到了这些错误
- .net - BotFramework v4:以编程方式将消息推送到特定渠道/个人用户/组
- python - 如何单独保存每个带有颜色条的图?