Your code would have worked if not for the fact that your Sort functions are mutating the state variable. Yes, sort
will mutate the original array and thus this:
const newcolors = colors.sort((a, b) =>
a.title > b.title ? 1 : b.title > a.title ? -1 : 0
);
actually alters your colors
state variable. Of course, that's a no no in React. I will show you how to make your SortbyTitle
function work and you can do the same for the other Sort functions as well. You need to create a copy of the sate variable and only then use sort
on it. Try this:
const SortbyTitle = () => {
const copy_of_ar = JSON.parse(JSON.stringify(colors));
copy_of_ar.sort((a, b) =>
a.title > b.title ? 1 : b.title > a.title ? -1 : 0
);
setColors(copy_of_ar);
};
And here is a Sandbox for you with a working Title sorter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…