[英]Sorting function by desc, asc
我有帶有列數組和數據數組的表組件。 我需要排序列並更新表的表狀態。 我的方法從列接收兩個參數鍵 (列鍵)和可排序的 (可對或不對的真或假列),我怎么辦? 排序表列的最佳解決方案是什么? 如何使其簡單,並按數字和字符串排序
const columns = [
{
key: 'deviceType',
label:'Device Type',
numeric: false,
}, {
key: 'deviceID',
label:'Device ID',
sortable: true,
numeric: true,
// cellRenderer: ({item, key}) =>
// <Button >Default</Button>,
}, {
key: 'name',
label: 'Name',
sortable: false,
numeric: false,
},{
key: 'currentVersion',
label: 'Current Version',
sortable: false,
numeric: false,
},{
key: 'location',
label: 'Location',
sortable: false,
numeric: false,
},{
key: 'status',
label: 'Status',
sortable: false,
numeric: false,
},{
key: 'lastAliveMessage',
label: 'Last alive message',
sortable: false,
numeric: false,
}, {
key: 'action',
label: 'Actions',
cellRenderer: () => <SimpleMenu />,
}]
const data = [
{ key: 1, deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ key: 2, deviceType: 'Tag', deviceID: 2, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ key: 3, deviceType: 'Tag', deviceID: 3, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ key: 4, deviceType: 'Tag', deviceID: 4, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ key: 5, deviceType: 'Tag', deviceID: 5, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
]
class EnhancedTable extends Component {
state = {
selected: [],
data,
order: 'asc',
search: '',
}
handleRequestSort = (key, sortable) => {
let order = 'desc'
// if (this.state.order.by === key && this.state.order.direction === 'desc') {
// order = 'asc'
// }
if (sortable && this.state.order.direction === 'desc') {
order = 'asc'
}
const data = this.state.data.sort(
(a, b) => {
order === 'desc' ? b[key] > a[key] : a[key] > b[key]},
)
this.setState({ data, order })
}
sort
執行原位數組修改。 而且你忘了回來。
const data = this.state.data.slice()
data.sort(
(a, b) => {
return order === 'desc' ? b[key] > a[key] : a[key] > b[key]
},
)
或刪除{}
data.sort(
(a, b) => (order === 'desc' ? b[key] > a[key] : a[key] > b[key]),
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.