React中对比两个动态数组实现关注/已关注按钮文本切换问题
问题根因
你当前的写法是判断两个数组是否存在公共元素,只要有任意一个匹配项,所有遍历生成的按钮都会返回true显示「Following」,没有针对当前遍历的单个用户做判断,所以不符合需求。
修正步骤
- 首先调整数组定义的兜底逻辑,避免加载状态下数组为布尔值导致调用数组方法报错:
// 加载状态下兜底为空数组,保证后续数组方法调用不会报错 const myFollowers = followerLoading ? [] : followersData.map((e) => e.requested_profile.Userlink ) const myFollowings = followingLoading ? [] : followingData.map((e) => e.requesting_profile.Userlink)
- 遍历每个粉丝时,针对当前遍历的用户标识判断是否在你的关注列表中,将map内部的btntext判断逻辑修改为:
const btntext = myFollowings.includes(e.requested_profile.Userlink) ? "Following" : "Follow"
修正后的完整渲染代码
!followerLoading && ( followersData.map((e) => { // 仅判断当前遍历的用户是否在你关注的列表中 const btntext = myFollowings.includes(e.requested_profile.Userlink) ? "Following" : "Follow" return(<> <div className="data"> <Grid templateColumns="repeat(2, 1fr)" width="100%" alignContent="center"> <GridItem w="100%" > <Flex mt="10px"> <Avatar size={isTabletOrMobile ? "xs" : "sm"} src={e.requested_profile.s3PicURL} /> <Text w="100%" wrap="off" ml="5px" isTruncated fontSize={isTabletOrMobile ? "sm" : "md"} > {e.requested_profile.Userlink} </Text> </Flex> </GridItem> <GridItem> <Flex justifyContent="flex-end"> <Button w="100px" h="30px" mt="8px" width={isTabletOrMobile ? "50px" : "60px"}> {btntext} </Button> </Flex> </GridItem> </Grid> </div> </> ) }) )
性能优化建议
如果关注列表数据量较大,可以提前将myFollowings转换为Set结构,将查找复杂度从O(n)降低到O(1):
const followingSet = new Set(myFollowings) // 遍历判断时替换为 const btntext = followingSet.has(e.requested_profile.Userlink) ? "Following" : "Follow"
内容的提问来源于stack exchange,提问作者Pratham Sampat
相关产品推荐
相关产品推荐

