React Native Feed页报TypeError读取undefined的uid,无法获取发帖人用户名
错误原因
- 你直接复用了Profile页的代码,Feed页面跳转时没有携带
route.params.uid参数,导致props.route.params为undefined,读取uid时触发报错。 firebase.auth().currentUser在用户未登录状态下也是undefined,直接读取uid也会触发同类型报错。- 你只在组件顶层调用了一次
useUser,查询的是路由参数对应的单个用户,Feed列表里每个帖子来自不同用户,自然拿不到对应发帖人的用户名。
修复方案
- 删掉Feed组件中不需要的路由uid查询代码,给currentUser加可选链防错,未登录时做兜底处理。
- 你已经通过redux拿到了全量用户列表
props.users,直接在渲染每个帖子时匹配对应发帖人即可,不需要额外调用useUser。 - 确保你存储帖子到Firestore时,每个post文档里都保存了发帖人的uid字段(示例中假设字段名为
creatorUid,你可以替换成自己实际的字段名)。
修改后核心代码
function Feed(props) { const classes = useStyles(); // 加可选链防用户未登录时报错 const currentUid = firebase.auth().currentUser?.uid; const posts = useAllPosts(currentUid); // 用户未登录兜底 if (!currentUid) return <Text>请先登录</Text> // 用户数据未加载完兜底 if (!props.usersLoaded) return <Text>加载中...</Text> return ( <ScrollView style={styles.root}> <FlatList numColumns={1} horizontal={false} data={posts} renderItem={({ item }) => { // 匹配当前帖子对应的发帖人 const postAuthor = props.users.find(u => u.uid === item.creatorUid) return ( <View style={styles.containerImage}> <Image style={styles.image} key={item.downloadURL + `?${new Date()}`} source={{ uri: item.downloadURL }} /> <View style={styles.container}> <Avatar className={classes.avatar} src={postAuthor?.avatar}></Avatar> <Typography className={classes.text}>{postAuthor?.name || '匿名用户'}</Typography> </View> <Text style={styles.containerInfo}>{item.caption}</Text> <Divider /> </View> ) }} /> </ScrollView> ); }
额外说明
如果你不想用redux里的用户数据,也可以把每个帖子项封装成独立的<PostItem />组件,在子组件内部调用useUser(item.creatorUid)查询用户信息,hook不能直接在FlatList的renderItem回调中使用,必须放在组件顶层。
内容的提问来源于stack exchange,提问作者chin14
相关产品推荐
相关产品推荐

