reactjs - reactjs中如何对数组进行排序
问题描述
我想在 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 排序
谢谢你的帮助
解决方案
您可以使用“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
推荐阅读
- php - Nette 框架 - Nette\Database\ResultSet 仅实现一种方式迭代器
- android - react-native-webview 中的 Google 登录似乎不起作用。大佬们有什么解决办法吗?
- python - SciPy optimize.curve 给出了一个拟合函数的两个拟合图
- python - 芹菜工人没有收到广播任务
- javascript - 无法绑定到“checked”,因为它不是“mat-button-toggle”的已知属性。在角度 9
- r - R上的简单高斯过程模拟
- php - 方法 Illuminate\Http\UploadedFile::resize 使用 laravel 6 不存在
- reactjs - 使用子箭头函数更改父级状态,React
- c# - 如何在 IEnumerable 和 IQueryable 之间干燥查询逻辑?
- mongodb - 当我的默认数组为空时,为什么猫鼬会用空字符串调用我的验证器?