【问题标题】:How to sort array in reactjsreactjs中如何对数组进行排序
【发布时间】:2019-08-31 13:19:28
【问题描述】:

我想在 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 排序

感谢您的帮助

【问题讨论】:

    标签: reactjs sorting filter axios


    【解决方案1】:

    您可以使用“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

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 1970-01-01
      • 2017-12-31
      • 2015-12-27
      • 2021-12-12
      • 1970-01-01
      • 2018-10-09
      • 2014-08-05
      • 2019-04-09
      相关资源
      最近更新 更多