配置react-redux-firebase与redux-firestore时firestoreConnect报错:Collection is required
解决react-redux-firebase中“Collection is required to build query name”错误
这个错误指向性很强——你的firestoreConnect配置里没有正确指定要连接的Firestore集合,或者配置格式出了问题。我之前配置的时候也踩过类似的坑,给你梳理一下排查和解决的步骤:
首先检查你的firestoreConnect调用格式
firestoreConnect要求你传递一个包含查询配置对象的数组,每个查询对象必须包含collection字段,这是构建查询名称的核心依据。
常见错误场景
- 传递了空参数或者空数组:
// 错误写法:没有指定任何查询 firestoreConnect() // 或者 firestoreConnect([]) - 查询对象里缺少
collection字段:// 错误写法:只指定了doc,没带collection firestoreConnect([{ doc: 'single-document' }]) - 动态查询时返回了无效的配置:
// 错误写法:条件判断后可能返回没有collection的对象 firestoreConnect(props => { if (props.someCondition) { return [{ doc: 'test' }] // 缺少collection } return [] })
正确的配置示例
1. 连接单个静态集合
import { firestoreConnect } from 'react-redux-firebase'; import { connect, compose } from 'react-redux'; class YourComponent extends Component { render() { // 从redux store中获取数据 const { posts } = this.props; return ( <div> {posts && posts.map(post => <div key={post.id}>{post.title}</div>)} </div> ); } } export default compose( // 正确配置:指定要连接的集合 firestoreConnect([ { collection: 'posts' } // 这里的collection字段是必须的 ]), connect(state => ({ // 对应store中firestore.ordered下的集合名称 posts: state.firestore.ordered.posts })) )(YourComponent);
2. 动态查询(依赖组件props)
如果需要根据props来过滤数据,确保返回的查询对象依然包含collection:
firestoreConnect(props => [ { collection: 'posts', where: ['authorId', '==', props.currentUser.uid] // 基于props的条件查询 } ])
3. 获取单个文档
如果要获取单个文档,也必须同时指定collection和doc字段:
firestoreConnect([ { collection: 'posts', doc: 'post-123' // 必须配合collection一起使用 } ])
函数组件的useFirestoreConnect钩子用法
如果你用的是函数组件,用useFirestoreConnect时也要遵循同样的规则:
import { useFirestoreConnect } from 'react-redux-firebase'; import { useSelector } from 'react-redux'; function PostDetail() { // 正确配置集合和文档 useFirestoreConnect([ { collection: 'posts', doc: 'post-123' } ]); const post = useSelector(state => state.firestore.data.posts['post-123']); return post ? <div>{post.title}</div> : <div>Loading...</div>; }
最后再排查一遍
- 确认你的每个查询配置对象都有
collection字段 - 如果是动态查询,确保所有分支返回的配置都符合要求
- 检查是否拼写错误(比如把
collection写成了collections)
内容的提问来源于stack exchange,提问作者Martin Reiche
相关产品推荐
相关产品推荐

