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

如何根据数组长度条件执行useCollection Hook?解决Firebase查询报错

问题:根据数组长度有条件执行自定义Hook中的useCollection

我想创建一个自定义Hook,用来调用react-firebase-hooks库中的useCollection Hook。项目采用Redux Toolkit作为状态管理器,Redux会为这个自定义Hook提供游戏数据。我需要从Store中获取已连接玩家的ID:game.players: string[]。但存在两种情况:游戏数据可能尚未完成加载(值为null),或是新创建的游戏没有任何已连接玩家。

我当前的实现代码:

export const useGamePlayers = () => {
    const {game} = useTypedSelector(state => state.game);

    return useCollection(
        query(collection(db, 'players'), where(documentId(), 'in', game?.players))
    )
};

使用该Hook时出现错误:Uncaught FirebaseError: Invalid Query. A non-empty array is required for 'in' filters,原因是新创建的游戏没有已连接玩家,导致game.players为空数组。

核心问题:如何根据数组长度有条件地执行该Hook?


解决方案

你可以通过判断game是否存在、game.players是否为非空数组,来决定是否发起有效的Firestore查询。如果不满足条件,就返回一个和useCollection Hook返回格式一致的默认状态,避免触发无效查询。

修改后的代码示例:

export const useGamePlayers = () => {
    const { game } = useTypedSelector(state => state.game);

    // 仅当game存在且players数组非空时,才构建有效查询
    const playersQuery = game?.players?.length > 0 
        ? query(collection(db, 'players'), where(documentId(), 'in', game.players))
        : null;

    // 传入null时,useCollection不会发起请求,返回默认未加载状态
    return useCollection(playersQuery);
};

补充说明

  • 当playersQuery为null时,useCollection不会发起Firestore请求,会返回[null, false, null](对应数据、加载状态、错误),你可以在组件中根据这个状态做对应处理,比如显示"暂无玩家"提示。
  • 如果需要更贴合业务的状态返回,也可以手动返回自定义值(比如无玩家时返回[[], false, null]),但要保证返回格式和useCollection一致,避免组件出现类型错误。

内容的提问来源于stack exchange,提问作者Антон Стецюра

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:50:27