In Javascript, sort
method performs in-place sorting. So, when you are performing people.sort
, you actually end up modifying the passed people
prop. Since arrays are passed by reference, every other reference of people
will show up the new sorted value.
To fix this, You should mutate a local copy of the passed prop to prevent such unexpected outcomes.
const Page2 = ({ people, digits }) => {
const sortedPeople = [...people].sort((a, b) => b.toLowerCase().localeCompare(a.toLowerCase()))
const sortedDigits = [...digits].sort((a,b)=>b-a);
return (
<div>
<h1>
Number Should Be "10" And Name Should Be "sally" On This Page When Sort
Is Uncommented
</h1>
<p>Number: {sortedDigits[0]}</p>
<p>Name: {sortedPeople[0]}</p>
</div>
);
};
export default Page2;
To further explain whats going on in the above approach,
Instead of directly mutating the prop, we are now creating a copy of the array, in this case people
and digits
by using a ES6 spread operator like this [...people]
and sorting on this new copy.
const sortedPeople = [...people].sort((a, b) => b.toLowerCase().localeCompare(a.toLowerCase()))
PS. You can also do Array.from(people)
or people.slice()
to achieve the same result.
Keep in mind, you can further optimise the rendering performance of this in React by using a useMemo
hook and do something like this
const sortedPeople = useMemo(() => [...people].sort((a, b) => b.toLowerCase().localeCompare(a.toLowerCase())), [people]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…