javascript - 如何在 React hooks 中对数组进行排序后渲染
我通过 props 获取一个包含对象的数组,然后我需要对它们进行排序并渲染,但现在我得到了数组并在排序后却无法渲染排序后的数组。我使用了 useEffect,在那里对数组进行排序,并通过 setState 将排序后的数组放入变量中,但当我尝试渲染时,出现数组为空的错误。我该如何解决?也许我可以用 newFriends 某种方式替换 props.friendsList?那样会很棒!
type FriendsProps = {
friendsList:
{
"id": number,
"firstName": string,
"lastName": string,
"photoUrl": string,
"online": boolean
}[]
}
const Friends: React.FC<FriendsProps> = (props) => {
const [friends, setFriends] = useState([{}]);
useEffect(() => {
const newFriends = props.friendsList.sort((friendA, friendB) => {
return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
})
setFriends(newFriends)
}, []);
console.log(friends)
return (
<div className="friends-list">
{friends.map((friendInfo, id) => {
return (
<h1>{friendInfo.firstName}</h1>
)
})}
</div>
);
};
console.log(friends) 最初显示为空数组,然后被填充
答案#1
我认为直接对朋友进行排序会更好。useEffect 和 state 是不必要的。为了保持优化,你应该使用 useMemo,但是你需要确保 props.friendsList 在每次渲染时不会改变:
const Friends: React.FC<FriendsProps> = props => {
const sortedFriends = React.useMemo(
() =>
props.friendsList.sort((friendA, friendB) => {
return friendA.online === friendB.online ? 0 : friendA.online ? -1 : 1;
}),
[props.friendsList]
);
console.log({sortedFriends});
return (
<div className='friends-list'>
{/* now map over your sortedFriends array */}
{sortedFriends.map((friendInfo, id) => {
// add a key when you're mapping over an array
return <h1 key={id}>{friendInfo.firstName}</h1>;
})}
</div>
);
};
