Firebase Web v9使用react-firebase-hooks时collection不是函数报错如何解决
报错原因与解决方案
报错原因
你使用了Firebase Web v9的模块化API体系,但仍沿用了v8及更早版本的命名空间链式调用写法,db.collection()属于已被v9废弃的API,因此调用时会抛出类型错误。
解决方案
首先确认你安装的react-firebase-hooks版本≥5.0.0,该版本开始支持Firebase v9的模块化入参格式,低于该版本需先升级依赖。
代码修改步骤
- 从
firebase/firestore导入模块化的查询构造方法:
import { collection, orderBy, query } from 'firebase/firestore'; import { useCollection } from 'react-firebase-hooks/firestore';
- 替换
useCollection的入参为v9规范的查询对象:
const [realtimePosts, loading, error] = useCollection( query( collection(db, 'posts'), orderBy('timestamp', 'desc') ) );
注意事项
- 不要混用Firebase v8兼容层写法和v9模块化写法,避免出现其他类型冲突问题
- 所有原v8版本的
db.xxx()链式调用都要替换为对应的模块化方法构造
内容的提问来源于stack exchange,提问作者user11881335
相关产品推荐
相关产品推荐

