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

标签 javascript reactjs react-redux

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 获取排序后的名称。但我没有从上面的代码片段中得到任何积极的结果。请让我知道我做错了什么?

最佳答案

不能直接在对象数组中使用排序函数。为此,您需要编写一个排序函数或编写一个回调函数,您可以根据需要进行修改。这是工作代码(https://stackblitz.com/edit/react-31un7h):

import React, { Component } from 'react';
import { render } from 'react-dom';
const SortNames  = (props) =>  {
        return (
           <span > 
            {props.names.name}
         </span>
        )
}
class LifeCycleComps extends Component {
  constructor(props) {
      super(props);
      this.state = {
        data: 0,
        names: [{
            name: "sam"
          },
          {
            name: "hammer"
          },
          {
            name: "jellyfish"
          }
        ]
      };

  }
   compare = ( a, b ) =>  {
      if ( a.name < b.name ){
        return -1;
      }
      if ( a.name > b.name ){
        return 1;
      }
      return 0;
}
  //below is sortAlphabet function
      sortAlphabet = () => {
        this.setState({
          names: this.state.names.sort(this.compare)
        });
      };
      render(){
        return (
          <div>
          <button onClick={this.sortAlphabet}>sort</button>
            <ul>
              {this.state.names.map((item, i) => (
              <SortNames key={i} names={item} /> ))}
            </ul>
          </div>
        );
      }
}



      //sortNames component


class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {
    return (
      <div>
        <LifeCycleComps/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));


关于javascript - 如何在 ReactJs 中对数组数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59454997/

相关文章:

javascript - 将 'sticky' 定位到容器的底部而不滚动

javascript - 特定组件的 PropTypes?

javascript - React Router Redux 从 v3 升级到 v4

javascript - Angular:子路由匹配

javascript - JSDoc:在另一个@param 中引用方法的@param

javascript - TinyMCE 编辑器中的目标元素

javascript - 将 html 标签放入字符串中

javascript - 能够在 TextField 中输入制表符吗?

reactjs - 如何从mapDispatchToProps内部访问状态

javascript - 未找到 React Redux Store 变量,即使它在存储中