如何在React TypeScript中按分数对帖子进行降序排序?
如何实现Chakra UI帖子按分数降序排序?
我正在使用Chakra UI创建4个帖子,每个帖子拥有独立的分数及详情,分数由点赞、评论和分享数量计算得出。相关代码如下:
Post组件及类型定义
export type PostProps = { id: string name: string dateTime: string message: string likes: number comments: number shares: number avatar: string media: string score?: number } export const Post = (props: PostProps) => { return ( <Box p="3" minW="sm" maxW="sm" borderWidth="1px" borderRadius="lg" overflow="hidden" fontWeight="semibold"> <Text align="right"> score: {props.score} </Text> <HStack> <Avatar size="md" name={props.name} src={props.avatar} /> <VStack spacing="0.5" align="-moz-initial"> <Text align="left">{props.name}</Text> <Text align="left" color="gray.500" fontWeight="semibold" fontSize="xs"> {props.dateTime} </Text> </VStack> </HStack> <Container p="1" fontWeight="normal"> {props.message} {props.media && <Image src={props.media} alt="" p="1" fit="cover" />} </Container> <HStack spacing="0.5"> <Icon as={AiFillLike} color="#E65300"></Icon> <Text p="1" fontSize="xs"> {props.likes} {props.comments} {props.shares} </Text> <Icon as={AiOutlineShareAlt}></Icon> </HStack> </Box> ) }
当前父组件渲染代码
return ( <VStack> <AlgoTester></AlgoTester> <Post id="1" name="Mr.Cat 1" dateTime={CurrentDate()} /*"23m"*/ message="Hello from the other side!" likes={RandomNumber()} comments={RandomNumber()} shares={RandomNumber()} avatar="https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg" media="https://img.freepik.com/premium-vector/boy-waving-hand-greeting-cute-people-illustration_107355-500.jpg?w=1380" score={200} /> <Post id="2" name="Mr.Cat 2" dateTime={CurrentDate()} /*"1d"*/ message="Seek success, but always be prepared for random cats." likes={RandomNumber()} comments={RandomNumber()} shares={RandomNumber()} avatar="https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg" media="https://img.freepik.com/premium-vector/smiling-young-man-showing-thumbs-up-illustration-hand-drawn-style_213307-233.jpg?w=1380" score={100} /> <Post id="3" name="Mr.Cat 3" dateTime={CurrentDate()} /*"4h"*/ message="Sometimes I stare at a door or a wall and I wonder what is this reality, why am I alive, and what is this all about?" likes={RandomNumber()} comments={RandomNumber()} shares={RandomNumber()} avatar="https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg" media="https://img.freepik.com/premium-vector/big-obstacle-concept-illustration_1133-825.jpg?w=1800" score={800} /> <Post id="4" name="Mr.Cat 4" dateTime={CurrentDate()} /*"14m"*/ message="Football is a family of team sports that involve, to varying degrees, kicking a ball to score a goal. Unqualified, the word football normally means the form of football that is the most popular where the word is used. Sports commonly called football include association football (known as soccer in North America and Oceania); gridiron football (specifically American football or Canadian football); Australian rules football; rugby union and rugby league; and Gaelic football. These various forms of football share to varying extent common origins and are known as football codes." likes={RandomNumber()} comments={RandomNumber()} shares={RandomNumber()} avatar="https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg" media="" score={250} /> </VStack> )
请问如何实现这些帖子按分数降序排序?
解决方案
要实现帖子按分数降序排序,只需三步:
1. 将帖子数据提取为数组
把原本分散的Post组件props整理成一个数组,方便后续排序操作:
const posts = [ { id: "1", name: "Mr.Cat 1", dateTime: CurrentDate(), message: "Hello from the other side!", likes: RandomNumber(), comments: RandomNumber(), shares: RandomNumber(), avatar: "https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg", media: "https://img.freepik.com/premium-vector/boy-waving-hand-greeting-cute-people-illustration_107355-500.jpg?w=1380", score: 200 }, { id: "2", name: "Mr.Cat 2", dateTime: CurrentDate(), message: "Seek success, but always be prepared for random cats.", likes: RandomNumber(), comments: RandomNumber(), shares: RandomNumber(), avatar: "https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg", media: "https://img.freepik.com/premium-vector/smiling-young-man-showing-thumbs-up-illustration-hand-drawn-style_213307-233.jpg?w=1380", score: 100 }, { id: "3", name: "Mr.Cat 3", dateTime: CurrentDate(), message: "Sometimes I stare at a door or a wall and I wonder what is this reality, why am I alive, and what is this all about?", likes: RandomNumber(), comments: RandomNumber(), shares: RandomNumber(), avatar: "https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg", media: "https://img.freepik.com/premium-vector/big-obstacle-concept-illustration_1133-825.jpg?w=1800", score: 800 }, { id: "4", name: "Mr.Cat 4", dateTime: CurrentDate(), message: "Football is a family of team sports that involve, to varying degrees, kicking a ball to score a goal. Unqualified, the word football normally means the form of football that is the most popular where the word is used. Sports commonly called football include association football (known as soccer in North America and Oceania); gridiron football (specifically American football or Canadian football); Australian rules football; rugby union and rugby league; and Gaelic football. These various forms of football share to varying extent common origins and are known as football codes.", likes: RandomNumber(), comments: RandomNumber(), shares: RandomNumber(), avatar: "https://upload.wikimedia.org/wikipedia/commons/4/48/RedCat_8727.jpg", media: "", score: 250 } ];
2. 对数组按分数降序排序
使用数组的sort方法,注意处理score为可选值的情况(默认按0处理):
const sortedPosts = [...posts].sort((a, b) => { // 处理score为undefined的情况,默认设为0 const scoreA = a.score ?? 0; const scoreB = b.score ?? 0; // 降序排序:分数高的在前 return scoreB - scoreA; });
这里用[...posts]创建数组副本,避免修改原数组。
3. 渲染排序后的帖子数组
用map遍历排序后的数组,生成Post组件:
return ( <VStack> <AlgoTester /> {sortedPosts.map(post => ( <Post key={post.id} {...post} /> ))} </VStack> );
额外优化:自动计算分数
既然分数由点赞、评论、分享数量计算,你可以直接在数组中自动计算score,不用手动传入:
// 假设分数计算规则:点赞*1 + 评论*2 + 分享*3(可根据需求调整) const posts = [ { // ...其他属性 likes: RandomNumber(), comments: RandomNumber(), shares: RandomNumber(), // 自动计算score get score() { return this.likes + this.comments * 2 + this.shares * 3; } }, // ...其他帖子 ];
这样修改后,帖子就会自动按分数从高到低排列了。
内容的提问来源于stack exchange,提问作者intothethickofit
相关产品推荐
相关产品推荐

