React 通过从 Angular 过滤来执行排序的方法是什么?
在这个例子中,您将如何按年龄对动物进行排序?
代码笔
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>
)
}
}
您需要做的就是在渲染对象时对对象进行排序:
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>
)
}
你可以使用 lodash
只需将其安装为依赖项
即可npm install --save lodash
并导入它
let _ = require('loadash')
render() {
let {animals} = this.state;
let animalsByAge = _.orderBy(animals, 'age')
return (
<div>
{animalsByAge.map((animal)=>{
return (<p key={animal.id}>{animal.type}</p>)
})}
</div>
)
}