React Native中Firebase连接失败:未创建默认Firebase应用
解决 "no firebase app 'default' has been created" 错误及代码优化建议
嘿,我帮你找到了问题的核心原因,还有几个小细节需要调整,让你的App正常跑起来:
1. 导致Firebase初始化失败的直接原因
你在App.js里把生命周期方法名拼错了!coponentWillMount() → 正确的写法是componentWillMount()。因为这个拼写错误,Firebase的初始化代码根本没有被执行,所以才会抛出下面的错误:
no firebase app 'default' has been created - call firebase app.initializeapp() (app/no-app)
另外要提醒你,componentWillMount在React的新版本中已经被标记为过时(deprecated),更推荐用componentDidMount来做初始化操作,或者直接在组件的constructor里初始化Firebase,这两种写法更安全:
// 推荐写法1:使用componentDidMount componentDidMount() { firebase.initializeApp({ apiKey: "xxxxxxxxxxxxxxxxxxx", authDomain: "xxxxxxxxxx", databaseURL: "xxxxxxxx", projectId: "xxxxxxxxxx", storageBucket: "", messagingSenderId: "xxxxxxxx" }); } // 推荐写法2:在constructor中初始化 constructor(props) { super(props); firebase.initializeApp({ // 你的Firebase配置信息 }); }
2. Login组件里的潜在问题(不修复登录功能会失效)
除了上面的核心错误,你的Login.js里还有几个小bug:
- 未正确引用state变量:
onButtonPress方法里的email和password没有加this.state前缀,应该改成this.state.email和this.state.password(或者用解构赋值更简洁) - 拼写错误:
cacth→ 正确的是catch - Props类型未定义:组件声明
class Login extends Component<Props>,但没有定义Props类型,需要在开头添加type Props = {};,或者直接去掉<Props>写成class Login extends Component - 方法调用方式错误:
onAuthSuccess().bind(this)会直接执行方法,而不是传递函数引用,应该改成this.onAuthSuccess.bind(this),或者把方法改成箭头函数避免手动绑定
修复后的onButtonPress和相关方法示例:
// 先把方法改成箭头函数,省去bind的麻烦 onAuthSuccess = () => { this.setState({ email: '', password: '', error: '', loading: false }) } onAuthFailed = () => { this.setState({ error: "Authentication Failed", loading: false }) } onButtonPress = () => { const { email, password } = this.state; // 解构赋值更简洁 this.setState({error: '', loading: true}); firebase.auth().signInWithEmailAndPassword(email, password) .then(this.onAuthSuccess) .catch(() => { firebase.auth().createUserWithEmailAndPassword(email, password) .then(this.onAuthSuccess) .catch(this.onAuthFailed) }) }
按照上面的步骤修改后,先解决Firebase初始化的问题,再调整Login组件的细节,你的应用应该就能正常运行啦!
内容的提问来源于stack exchange,提问作者Waeez
相关产品推荐
相关产品推荐

