如何按升序和降序对列进行排序?

时间:2020-07-19 20:37:58

标签: javascript arrays reactjs sorting

我是使用对象数组创建的表,现在我并没有理解如何通过单击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

2 个答案:

答案 0 :(得分:2)

  • 您需要将onChange处理程序切换为onClick
  • 添加一些状态以存储最后的排序方向;
  • 使用数组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>

Edit dawn-paper-1bh7t

答案 1 :(得分:0)

添加状态变量以进行升序或降序排序,然后在您的排序函数中:

function Sort(a,b){
    if(this.state.ascending){
        return a.id - b.id
    {
    return b.id - a.id
}

然后在渲染函数中,在地图之前添加sort方法:

const Data = [...this.state.Data]
//...

      Data.sort((a,b)=>this.Sort(a,b)).map((item,index)=>(
        <tr key={item.id}>           
          <td >{item.id}</td>        
          <td >{item.fullName}</td>
          <td>{item.email}</td>
        </tr>
              
               

最后更改您的onClick以仅更改升/降状态:

 <th onClick={()=>this.setState({ascending: !this.state.ascending)}>ID</th>