Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 对数组进行升序和降序排序_Reactjs_Sorting - Fatal编程技术网

Reactjs 对数组进行升序和降序排序

Reactjs 对数组进行升序和降序排序,reactjs,sorting,Reactjs,Sorting,我正在尝试将数据从升序排序到降序排序。这是我的代码: const onSort = (sortKey) => { let sortCustomer = [...customers]; sortCustomer.sort(function(a, b){ if(a[sortKey] < b[sortKey]) { return -1; } if(a[sortKey] > b[sortKey]) { return 1; } return 0;

我正在尝试将数据从升序排序到降序排序。这是我的代码:

  const onSort = (sortKey) => {
  let sortCustomer = [...customers];
  sortCustomer.sort(function(a, b){
    if(a[sortKey] < b[sortKey]) { return -1; }
    if(a[sortKey] > b[sortKey]) { return 1; }
    return 0;
  })
  setcustomers(sortCustomer);
const onSort=(sortKey)=>{
让sortCustomer=[…客户];
sortCustomer.sort(函数(a,b){
如果(a[sortKey]b[sortKey]){return 1;}
返回0;
})
setcustomers(sortCustomer);
}


升序工作,但降序不工作。

您的分拣机功能仅用于升序,对于降序,您应执行以下操作:

const onSort = (sortKey) => {
  let sortCustomer = [...customers];
  sortCustomer.sort(function(a, b){
    if(a[sortKey] < b[sortKey]) { return -1; }
    if(a[sortKey] > b[sortKey]) { return 1; }
    return 0;
  })

  // create a variable to determine whether to use ascending or descending order
  if (order === 'desc') {
    sortCustomer.reverse()
  }

  setcustomers(sortCustomer);
}
const onSort=(sortKey)=>{
让sortCustomer=[…客户];
sortCustomer.sort(函数(a,b){
如果(a[sortKey]b[sortKey]){return 1;}
返回0;
})
//创建一个变量以确定是使用升序还是降序
如果(顺序=='desc'){
sortCustomer.reverse()
}
setcustomers(sortCustomer);
}

传递给
sort()
的函数总是按升序排序,为什么希望它按降序排序

.sort(function(a, b){
    if(a[sortKey] < b[sortKey]) { return -1; }
    if(a[sortKey] > b[sortKey]) { return 1; }
    return 0;
  })
.sort(函数(a、b){
如果(a[sortKey]b[sortKey]){return 1;}
返回0;
})
要按降序排序,需要执行以下操作:

.sort(function(a, b){
    if(a[sortKey] < b[sortKey]) { return 1; }
    if(a[sortKey] > b[sortKey]) { return -1; }
    return 0;
  })
.sort(函数(a、b){
如果(a[sortKey]b[sortKey]){return-1;}
返回0;
})

“订单”未定义您必须自己定义,我不知道您的应用程序逻辑,因此这只是一个虚拟的编码结果文档: