You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Feed页报TypeError读取undefined的uid,无法获取发帖人用户名

错误原因

  1. 你直接复用了Profile页的代码,Feed页面跳转时没有携带route.params.uid参数,导致props.route.params为undefined,读取uid时触发报错。
  2. firebase.auth().currentUser在用户未登录状态下也是undefined,直接读取uid也会触发同类型报错。
  3. 你只在组件顶层调用了一次useUser,查询的是路由参数对应的单个用户,Feed列表里每个帖子来自不同用户,自然拿不到对应发帖人的用户名。

修复方案

  1. 删掉Feed组件中不需要的路由uid查询代码,给currentUser加可选链防错,未登录时做兜底处理。
  2. 你已经通过redux拿到了全量用户列表props.users,直接在渲染每个帖子时匹配对应发帖人即可,不需要额外调用useUser。
  3. 确保你存储帖子到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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:18:05