如何在ReactJS中的asc和desc中对数据进行排序

如何在ReactJS中的asc和desc中对数据进行排序

本文介绍了React:如何在ReactJS中的asc和desc中对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过API显示数据(数据以分页显示),API是在Loopback中构建的.我想对我的项目进行排序.例如,如果用户单击表头"属性,则它将按asc和desc对数据进行排序.我是新来的ReactJS,没有太多的知识来实现​​这种逻辑,请有人帮我弄清楚.谢谢

I am showing data through API ( Data is showing in Pagination ) , API were built in Loopback . I want to sort in my project . For example if User click on Table head attribute then It will sort data in asc and desc . I am new ReactJS don't have much knowledge to implement this logic, Could someone please help me to figure out . Thanks

代码

         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' ))

推荐答案

让我们假设您获取了数据,现在状态如下:

Let's assume that you fetched your data and now your state looks like this:

state ={
    data : [13,15,21,1,2]
}

现在服务器上的工作已经完成,您不必每次用户单击排序时都获取新数据,现在只需添加一个函数来处理用户单击,假设用户单击了 asc 命令,您的处理程序应如下所示:

Now the work on the server is done, you don't have to fetch new data every time the user click to sort, now just add a function to handle the user click, let's say that the use clicks on the asc order, your handler should look like this:

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)})
   }

}

这篇关于React:如何在ReactJS中的asc和desc中对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:53