首页 > 解决方案 > reactjs中如何对数组进行排序

问题描述

我想在 reactJS 中对数组进行排序

我尝试使用 sort() javascript 方法,但它没有对其进行排序。我已经实现了它可以工作的过滤器,但无法正常工作!



  constructor(props) {
    super(props);
    this.state = {
      persons: [],
      search: '',
      key: null,
      direction: {
        name: 'asc',
      }

    };
    this.sortBy = this.sortBy.bind(this);
  }

  componentDidMount(){
    axios.get(`https://jsonplaceholder.typicode.com/users`)
    .then(res => {
      console.log(res);
      this.setState({ 
        persons: res.data      
      });
    }); 
  }

  sortBy(e,key){
    console.log("keeo  "+key + "  - e  "+e.target.value); 

    this.setState({
      key: key
      persons: this.state.persons.sort( 
        (person) => { return 
        this.state.direction[key] === 'asc'
        ? 
        parseFloat(a[key]) - parseFloat(b[key])
        : parseFloat(b[key]) - parseFloat(a[key])
    })
      .direction: {
        [key]: this.state.direction[key] === 'asc' ? 'desc' : 'asc'
      }
    })
  }

  // inside render 

  <button onClick = {(e,name) => this.sortBy(e,'name')}>Name</button>
<button onClick = {(e,amount) => this.sortBy(e,'amount')}>amount</button>

<button onClick = {(e,city) => this.sortBy(e,'city')}>city</button>



我希望能够按 person.name、person.amount、person.city 排序

谢谢你的帮助

标签: reactjssortingfilteraxios

解决方案


您可以使用“lodash”库中的 sortBy 过滤器:

let sortedArrPersons = _.sortBy(persons, ['name', 'amount', 'city']);

例如:

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]

有关更多详细信息,请访问: https ://lodash.com/docs/4.17.11#sortBy


推荐阅读