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

Firebase查询matches集合报错:Expected type 'Ta', but it was: a custom oh object

问题解决:Firestore查询报错 Expected type 'Ta', but it was: a custom oh object

错误原因

你调用query函数的方式不符合Firestore API规范:Firestore的query函数第一个参数必须是集合引用对象,但你直接把db和集合名称字符串"matches"作为两个参数传入,导致Firestore无法识别正确的类型,从而抛出类型错误。同时你原代码中useEffect的回调结构也存在语法错误,拆分了逻辑导致无法正确执行。

修复后的完整代码

import { View, Text } from "react-native";
import React, { useEffect, useState } from "react";
import useAuth from "../hooks/useAuth";
import { onSnapshot, query, where, collection } from "firebase/firestore"; // 新增collection导入
import { db } from "../firebase";

const Chatlist = () => {
  const [matches, setMatches] = useState([]);
  const { user } = useAuth();

  useEffect(() => {
    // 先通过collection函数获取正确的集合引用
    const matchesCollection = collection(db, "matches");
    // 基于集合引用构建查询条件
    const matchesQuery = query(
      matchesCollection,
      where("userMatched", "array-contains", user.uid)
    );

    // 订阅查询快照的更新
    const unsubscribe = onSnapshot(matchesQuery, (snapshot) => {
      setMatches(
        snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }))
      );
    });

    // 组件卸载时取消订阅,避免内存泄漏
    return unsubscribe;
  }, [user]);

  // 示例渲染逻辑,可根据需求修改
  return (
    <View>
      {matches.length > 0 ? (
        matches.map(match => (
          <Text key={match.id}>{match.id}</Text>
        ))
      ) : (
        <Text>暂无匹配记录</Text>
      )}
    </View>
  );
};

export default Chatlist;

核心修复点

  • 新增collection函数导入:用于从数据库实例和集合名称生成合法的集合引用对象。
  • 修正查询构建逻辑:先通过collection(db, "matches")获取集合引用,再传入query函数搭配where条件。
  • 修复useEffect结构:将快照订阅逻辑整合到同一个回调函数中,并返回取消订阅函数以清理资源。

内容的提问来源于stack exchange,提问作者Honest Raj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:45:32