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

TS提示'{ docId: string; }'无userId属性 Firebase获取推荐用户返回null

问题修复方案

问题1:firebase.js filter逻辑处报Property 'userId' does not exist on type '{ docId: string; }'警告

原因

TypeScript仅能推断出map方法返回的对象包含docId字段,无法识别从Firebase拉取的user.data()中存在userId属性,因此抛出类型校验警告。

修复方案

  1. 先确认Firebase的users集合下所有文档确实存储了userId字段,如果用户文档的ID本身就是用户ID,可以直接替换userId为docId修改filter逻辑,即可消除警告:
.filter((profile) => profile.docId !== userId && !following.includes(profile.docId));
  1. 如果确定user.data()一定包含userId字段,也可以通过类型断言消除警告(TypeScript环境):
// 提前定义返回值类型
interface UserProfile {
  userId: string;
  docId: string;
  [key: string]: any;
}
// map时指定类型
.map((user) => ({ ...user.data(), docId: user.id} as UserProfile))

问题2:控制台输出profiles值为null

原因

你把console.log('profiles', profiles)写在了useEffect的同步执行流程中,suggestedProfiles是异步函数,调用后不会阻塞后续代码执行,打印日志时异步请求还未完成,setProfiles还未触发,因此拿到的是profiles的初始值null。

修复方案

  1. 将日志打印挪到异步请求完成后,即可查看接口实际返回值:
useEffect(() => {
  async function suggestedProfiles() {
      const response = await getSuggestedProfiles(userId, following );
      console.log('接口返回的推荐用户', response) // 此处打印可拿到真实接口返回
      setProfiles(response);
  }
  if (userId) {
    suggestedProfiles();
  }
}, [userId]);

// 若需要查看state更新后的profiles值,可单独加监听逻辑
useEffect(() => {
  console.log('state更新后的推荐用户', profiles)
}, [profiles])
  1. 额外增加入参合法性校验,避免因入参异常导致查询逻辑中断:
if (userId && Array.isArray(following)) {
  suggestedProfiles();
}

如果接口返回的response是空数组,说明当前没有符合过滤条件的推荐用户,属于正常业务逻辑,可自行调整渲染逻辑添加「暂无推荐」类的提示文案。


内容的提问来源于stack exchange,提问作者Tiisetso Dinoko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:57:04