使用Redux时Firebase数据无法加载,无法读取Firestore中categories集合数据
问题排查及解决方案
- 集合名大小写不匹配
Firestore 集合名称大小写敏感,你实际创建的集合名为小写categories,但代码中查询使用的是全大写"CATEGORIES",二者不一致会导致查询不到集合,先将查询代码修改为:
firestore.collection("categories")
- Redux 未配置异步中间件导致 action 未执行
你在loadCategories中返回的是 thunk 函数,默认 Redux store 仅支持处理普通对象类型的 action,不会执行你返回的异步函数,所以 Firestore 查询代码根本没有运行,控制台自然没有输出。
解决方案:安装配置 redux-thunk:
- 安装依赖:
npm install redux-thunk - 修改 store 创建代码,引入 thunk 中间件:
import { createStore, combineReducers, applyMiddleware } from 'redux' import thunk from 'redux-thunk' const store = createStore( combineReducers({ DEFAULT: DEFAULT_REDUCER, categories: categoryReducer, }), applyMiddleware(thunk) )
- categoryReducer 初始值不符合判断条件
你在componentDidMount中只有当this.props.categories === null时才会调用加载方法,如果你的categoryReducer初始值不是null(比如默认是undefined或者空数组),会导致加载方法从未被触发。
确认你的 categoryReducer 初始值设置如下:
const initialState = null const categoryReducer = (state = initialState, action) => { // 其余业务逻辑 }
- Firestore 配置异常
- 确认你已经完成 Firebase 初始化配置,代码中使用的
firestore实例是通过firebase.firestore()正确生成的有效实例 - 暂时将 Firestore 安全规则调整为测试模式验证读取功能是否正常:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } }
测试完成后请及时调整规则为符合业务要求的正式权限规则。
内容的提问来源于stack exchange,提问作者sambit
相关产品推荐
相关产品推荐

