I have this code and I'm supposed to alternate between upper case and lower case on click. I already have the sorts available but I need to write another method so that it alternates. The code I've written doesn't alternate but only sorts ascending and then stops. We need to modify the (sorting) method.
Code:
ascending() {
this.setState(prevState => {
const copy = [...prevState.cars];
copy.sort((a, b) => (a.year - b.year));
return { cars: copy };
});
}
descending() {
this.setState(prevState => {
const copy = [...prevState.cars];
copy.sort((a, b) => (b.year - a.year));
return { cars: copy };
});
}
sorting() {
let count=0;
if (count % 2 == 0) {
this.ascending();
count++;
} else {
this.descending();
count++;
}
}
Try below code. Don't forget to set default value for "toggleSorting" while initializing 'state' begining of the cycle.
sorting = () => {
const {
toggleSorting,
} = this.state;
if(toggleSorting) {
this.descending();
} else {
this.ascending();
}
this.setState({toggleSorting: !toggleSorting});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.