react-redux-firebase中如何向firestoreConnect传递auth/profile对象实现查询?
解决firestoreConnect中无法访问props.auth.uid的问题
我之前也碰到过一模一样的问题,踩过的坑给你分享下:
核心原因
你代码里报错TypeError: Cannot read property 'uid' of undefined,本质是组件初始化阶段,Firebase的auth状态还没同步到Redux Store里,这时候connect注入的props.auth还是undefined,firestoreConnect的回调函数执行时自然拿不到uid。而硬编码UID能正常工作,是因为不需要依赖异步加载的auth状态,直接用了有效值。
解决方案
这里给你两种靠谱的解决方式,选哪种都可以:
方案一:在firestoreConnect回调中做空值判断
先检查auth是否存在,避免报错,等auth状态加载完成后再添加查询条件:
export default compose( firebaseConnect(), firestoreConnect(props => { // 先判断auth和uid是否存在,防止空指针 if (!props.auth?.uid) { return []; // auth未加载时,暂时不添加查询规则 } return [{ collection: 'projects', where: [['uid', '==', props.auth.uid]] }]; }), connect((state, props) => ({ projects: state.firestore.ordered.projects, profile: state.firebase.profile, auth: state.firebase.auth, })) )(Projects);
方案二:直接从Redux Store中获取auth状态
firestoreConnect的回调函数支持第二个参数store,可以直接从中获取最新的auth状态,不用依赖组件props:
export default compose( firebaseConnect(), firestoreConnect((props, store) => { const { auth } = store.getState().firebase; if (!auth?.uid) { return []; } return [{ collection: 'projects', where: [['uid', '==', auth.uid]] }]; }), connect((state, props) => ({ projects: state.firestore.ordered.projects, profile: state.firebase.profile, auth: state.firebase.auth, })) )(Projects);
额外优化:组件内添加加载状态提示
为了提升用户体验,你可以在组件内部用react-redux-firebase提供的isLoaded工具函数,判断auth是否加载完成,再渲染内容:
import { isLoaded } from 'react-redux-firebase'; function Projects({ auth, projects }) { // 当auth未加载完成时,显示加载提示 if (!isLoaded(auth)) { return <div>加载中...</div>; } // auth加载完成后,渲染项目列表 return ( <div> {projects?.map(project => ( <div key={project.id}>{project.name}</div> ))} </div> ); }
内容的提问来源于stack exchange,提问作者user549385
相关产品推荐
相关产品推荐

