如何在ReactJs中对数组数据进行排序

问题描述 投票:0回答:2

class LifeCycleComps extends Component {
  constructor(props) {
      super(props);
      this.state = {
        data: 0,
        names: [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }
        ]
      };

      //below is sortAlphabet function
      sortAlphabet = () => {
        this.setState({
          names: this.state.names.sort()
        });
      };


      //sortNames component
      class SortNames extends Component {
        render() {
          return <span > {
            this.props.names.name
          } < /span>;
        }
      }
<button onClick={this.sortAlphabet}>sort</button>
<ul>
  {this.state.names.map((item, i) => (
  <SortNames key={i} names={item} /> ))}
</ul>

上面是我的代码,我不确定主要问题是什么,我只是想通过onClick获得排序的名称,但是我没有从上述代码片段中获得任何积极的结果,请让我知道大家我做错了什么。

javascript reactjs react-redux
2个回答
0
投票

这里是排序值

let arr = [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }]

function sortIt(x,y) {
  if ( x.name < y.name ){
    return -1;
  }
  if ( x.name > y.name ){
    return 1;
  }
  return 0;
}

arr.sort(sortIt);
console.log(arr);

0
投票

它只是为了适应注释中提供的javascript代码,如下所示。


compare = ( a, b ) => {
  if ( a.last_nom < b.last_nom ){
    return -1;
  }
  if ( a.last_nom > b.last_nom ){
    return 1;
  }
  return 0;
}

     //below is sortAlphabet function
sortAlphabet = () => {
  let objs = [...this.state.names]
  this.setState({
     names: objs.sort( compare );
  });
};



© www.soinside.com 2019 - 2024. All rights reserved.