ciao!
sto cercando di ordinare una tabella quando clicco sull'header:
codice:
import React from 'react';
import {
Table,
Card,
CardHeader,
CardBody
} from 'reactstrap';
import axios from 'axios';
import {BOOK_ALL} from "../config/config";
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
books: [],
cntBook: ''
};
this.compareBy.bind(this);
this.sortBy.bind(this);
};
compareBy(key) {
console.log(key);
return function (a, b) {
console.log(a);
console.log(b);
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
};
}
sortBy(key) {
let arrayCopy = [...this.state.books];
arrayCopy.sort(this.compareBy(key));
this.setState({books: arrayCopy});
}
componentDidMount() {
axios.get(BOOK_ALL)
.then(res => {
this.setState({
books: res.data.books,
cntBook: res.data.books.length
});
});
}
render() {
return (
<main role="main" className="container-fluid">
<Card>
<CardHeader>Totale libri: {this.state.cntBook}</CardHeader>
<CardBody>
<div className="table-responsive">
<Table size="sm" hover bordered>
<thead className="thead-dark">
<tr>
<th onClick={() => this.sortBy('title')}>Titolo</th>
<th>Autore</th>
<th>Editore</th>
<th>Prezzo</th>
<th>ISBN</th>
<th>Note</th>
</tr>
</thead>
<tbody>
{
this.state.books.map(book =>
<tr key={book.id}>
<td scope="row">{book.title}</td>
<td>{book.author}</td>
<td>{book.editor}</td>
<td>{book.price}</td>
<td>{book.isbn}</td>
<td>{book.note}</td>
</tr>
)
}
</tbody>
</Table>
</div>
</CardBody>
</Card>
</main>
);
}
}
non ricevo errori, ma la tabella non si ordina.
non riesco a capire dove sbaglio!
qualche idea??