我通过API显示数据(数据显示在分页中),API是在Loopback中构建的。我想在我的项目中排序。例如,如果用户单击表头属性,那么它将在asc和desc中对数据进行排序。我是新的ReactJS没有太多的知识来实现这个逻辑,有人可以帮我弄明白。谢谢
码
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
Item: 5,
skip: 0
}
this.handleClick = this.handleClick.bind(this);
}
urlParams() {
return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
handleClick() {
this.setState({skip: this.state.skip + 1})
}
render() {
return (
<div>
<a href={this.urlParams()}>Example link</a>
<pre>{this.urlParams()}</pre>
<button onClick={this.handleClick}>Change link</button>
</div>
)
}
}
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
假设您已获取数据,现在您的状态如下所示:
state ={
data : [13,15,21,1,2]
}
现在服务器上的工作已经完成,你不必每次用户点击排序时都要获取新数据,现在只需添加一个函数来处理用户点击,让我们说使用点击asc
命令,你的处理程序应该是这样的:
const clickHandler = order =>{
switch(order):{
case 'asc': return this.setState({data : this.state.data.sort((a,b)=> a-b) })
case 'desc' : return this.setState({data : this.state.data.sort((a,b) => b-a)})
}
}
semantic-ui-react已经支持sort函数。
检查此示例:https://react.semantic-ui.com/collections/table/#variations-sortable
import _ from 'lodash'
import React, { Component } from 'react'
import { Table } from 'semantic-ui-react'
const tableData = [
{ name: 'John', age: 15, gender: 'Male' },
{ name: 'Amber', age: 40, gender: 'Female' },
{ name: 'Leslie', age: 25, gender: 'Female' },
{ name: 'Ben', age: 70, gender: 'Male' },
]
export default class TableExampleSortable extends Component {
state = {
column: null,
data: tableData,
direction: null,
}
handleSort = clickedColumn => () => {
const { column, data, direction } = this.state
if (column !== clickedColumn) {
this.setState({
column: clickedColumn,
data: _.sortBy(data, [clickedColumn]),
direction: 'ascending',
})
return
}
this.setState({
data: data.reverse(),
direction: direction === 'ascending' ? 'descending' : 'ascending',
})
}
render() {
const { column, data, direction } = this.state
return (
<Table sortable celled fixed>
<Table.Header>
<Table.Row>
<Table.HeaderCell
sorted={column === 'name' ? direction : null}
onClick={this.handleSort('name')}
>
Name
</Table.HeaderCell>
<Table.HeaderCell
sorted={column === 'age' ? direction : null}
onClick={this.handleSort('age')}
>
Age
</Table.HeaderCell>
<Table.HeaderCell
sorted={column === 'gender' ? direction : null}
onClick={this.handleSort('gender')}
>
Gender
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{_.map(data, ({ age, gender, name }) => (
<Table.Row key={name}>
<Table.Cell>{name}</Table.Cell>
<Table.Cell>{age}</Table.Cell>
<Table.Cell>{gender}</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
)
}
}
要实现此行为,必须使用Loopback的“Order filter”:https://loopback.io/doc/en/lb3/Order-filter.html
因此,“id”字段上的过滤器应如下所示:
filter:{“where”:{},“order”:[“id ASC”],“limit”:15,“skip”:0}
filter:{“where”:{},“order”:[“id DESC”],“limit”:15,“skip”:0}