Angular订单的React方法是什么

Cri*_*alu 1 reactjs

从Angular 进行orderBy过滤的React方法是什么 ?

在此示例中,您如何按年龄订购动物?

密码笔

class Application extends React.Component {
  constructor(props){
    super(props);
    this.state={
      animals: [
        {id: 1, age: 5, type: "cat"}, 
        {id: 2, age: 3, type: "dog"},
        {id: 3, age: 10, type: "wolf"}
      ]
    }
  }
  render() {
    let {animals} = this.state;

    return (
      <div>
        {animals.map((animal)=>{
          return (<p key={animal.id}>{animal.type}</p>)
        })}
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*mid 6

您需要做的就是在渲染对象时对对象进行排序:

  render() {
    let {animals} = this.state;

    return (
      <div>
      {[...animals].sort((a,b) => {return a.age - b.age}).map((animal)=>{
        return (<p key={animal.id}>{animal.type}</p>)
      })}
    </div>
    )
  }
Run Code Online (Sandbox Code Playgroud)

  • 您需要先对动物进行切片。`sort`对项目进行分类!或使用undescore / lodash实用程序方法之一。原生的sort方法是不稳定的,因此在render中调用它可能不是最好的主意,因为它可以随机更改相等(具有相同年龄)的项的顺序。 (3认同)