Я бы хотел отсортировать массив в ReactionJS
Я пытался использовать метод javascript sort (), но он не сортируется. Я уже реализовал фильтр, который работает, но не смог заставить работать сортировку!
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
Спасибо за вашу помощь