React Native开发中调用firebase.auth()提示找不到变量firebase的问题
问题核心原因
你遇到的can't find variable : firebase报错本质是混用了不同版本Firebase SDK的调用方式:
- 你当前项目安装、导入的是React Native Firebase的模块化包,代码里已经从
@react-native-firebase/auth导入了可直接调用的auth方法,从@react-native-firebase/firestore导入了可直接调用的firestore方法 - 但你写代码时套用了Web端全局Firebase SDK的写法,去调用根本不存在的全局变量
firebase,自然会触发未定义变量的报错。
具体修改步骤
- 去掉代码里对全局
firebase对象的依赖,直接使用已导入的auth方法替换原来的firebase.auth()调用 - 把
onAuthStateChanged的普通回调函数改成箭头函数,避免普通函数内部this指向丢失,导致无法获取组件的this.state、this.props.navigation - 移除原代码里无实际作用的空then回调,简化逻辑
修改后的可用createUser函数代码
createUser = () => { auth().onAuthStateChanged((user) => { if (user) { // 已登录用户:执行Firestore写入逻辑 firestore() .collection('Users') .add({ NickName: this.state.NickName, Age: this.state.Age, City: this.state.City, Mail: this.state.Mail, MyTeam: [{ Activity: "", City: "", Members: [{ Mail: "", Pseudo: "" }], Owner: true }] }) .then(() => { this.props.navigation.navigate('Profil') }) } else { // 未登录用户的逻辑 console.log('coucou') } }); }
补充说明:Web端Firebase SDK的逻辑是将所有服务挂载到全局
firebase对象上,通过firebase.方法名()的形式调用服务;但React Native Firebase采用按需模块化导入的设计,每个功能的方法直接从对应的子包导入即可,不需要依赖全局firebase变量,你之前没加auth逻辑时可以正常运行,也是因为一直在用直接导入的firestore方法,没有调用不存在的全局变量。
内容的提问来源于stack exchange,提问作者Wendy Montagnon
相关产品推荐
相关产品推荐

