React Native Firebase认证注册报错与AsyncStorage警告咨询
问题背景
我是React开发初学者,近期尝试使用Firebase实现登录界面的身份认证功能,初始实现代码如下:
import { StyleSheet, Text, View, KeyboardAvoidingView,TextInput, TouchableOpacity } from 'react-native' import React, { useState } from 'react' import {auth} from '../firebase' const LogScreen = () => { const[email,setEmail] = useState() const[password,setPassword] =useState() const handleSignUp = ()=>{ auth .createUserWithEmailAndPassword(email, password) .then(userCredentials=>{ const user = userCredentials.user; console.log(user.email); }) .catch(error=>alert(error.message)) } return ( <KeyboardAvoidingView style={styles.container} behavior="padding"> <View style={styles.inputContainer}> <TextInput value ={email} defaultValue={''} onChangedText={(text)=>setEmail(text)} style = {styles.input} placeholder="Email" /> <TextInput value ={password} defaultValue={''} onChangedText={(text)=>setPassword(text) } style = {styles.input} placeholder="Password" secureTextEntry /> </View> <View style={styles.buttonContainer}> <TouchableOpacity onPress={()=>{}} style = {styles.loginButton} > <Text styles = {styles.buttonText}>Log in</Text> </TouchableOpacity> <TouchableOpacity onPress={handleSignUp} style = {styles.registerButton} > <Text styles = {styles.buttonText}>Register</Text> </TouchableOpacity> </View> </KeyboardAvoidingView> ) } export default LogScreen const styles = StyleSheet.create({ input:{ backgroundColor:'white', borderColor:'#ADD8E6', borderWidth:2, padding:5, margin:5, borderRadius:10, justifyContent:'center', alignItems:'center' }, container:{ flex:1, justifyContent:'center', alignItems:'center' }, inputContainer:{ width:'75%' }, buttonContainer:{ width:'100%', backgroundColor:'#CCCCFF', alignItems:'center' }, loginButton:{ borderRadius:10, width:'50%', backgroundColor:'#dca4c3', height:40, padding:5, textAlignVertical:'center', alignItems:'center', borderWidth:3, marginTop:10 }, buttonText:{ color:'white', fontWeight:'800', fontSize:8 }, registerButton:{ borderRadius:10, backgroundColor:'#dca4c3', width:'50%', height:40, padding:5, textAlignVertical:'center', alignItems:'center', borderWidth:3, marginTop:10 }, })
测试过程中遇到两个问题:
- 输入邮箱、密码后点击注册按钮,触发错误提示:
createUserWithEmailAndPassword failed: First argument "email" must be a valid string. - 在模拟器的Expo Go环境中启动应用时,弹出警告信息:
AsyncStorage has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-async-storage/async-storage' instead of 'react-native'
修复方案
注册接口参数错误修复
错误原因有三点:
- React Native中
TextInput组件监听文本输入变化的正确属性是onChangeText,代码中错写为onChangedText(多了字母d),导致输入内容时根本没有触发state更新,email和password始终是初始的undefined值,传给Firebase的注册方法时不符合参数类型要求。 - 两个state初始化时没有设置默认值,默认返回
undefined,进一步加剧了类型错误。 - 额外代码问题:
Text组件设置样式的正确属性是style,代码中错写为styles,会导致按钮文字样式不生效。
对应修复步骤:
- 将两个
TextInput的onChangedText属性全部改为onChangeText,删除多余的defaultValue属性(value已经和state绑定,不需要额外设置defaultValue) - 给
email、password两个state设置初始空字符串 - 修正两个按钮内
Text组件的样式属性名
修正后的核心代码片段:
// state初始化修正 const [email, setEmail] = useState('') const [password, setPassword] = useState('') // 输入框部分修正 <TextInput value={email} onChangeText={(text)=>setEmail(text.trim())} style={styles.input} placeholder="Email" autoCapitalize="none" /> <TextInput value={password} onChangeText={(text)=>setPassword(text)} style={styles.input} placeholder="Password" secureTextEntry /> // 按钮文字修正 <Text style={styles.buttonText}>Log in</Text> <Text style={styles.buttonText}>Register</Text>
补充优化:邮箱输入框加autoCapitalize="none"可以避免系统自动首字母大写导致的邮箱格式错误,输入邮箱时自动去除首尾空格也能减少无效输入问题。
AsyncStorage警告处理
警告含义
早期React Native核心库内置了AsyncStorage本地持久化模块,从v0.59版本开始,该模块被从核心库拆分出来作为独立社区包维护,未来React Native版本会彻底移除核心库中的AsyncStorage实现。当前触发警告是因为Firebase Auth SDK默认会尝试调用React Native核心库内置的旧版AsyncStorage做登录态持久化。
处理步骤
- 安装独立维护的AsyncStorage包,Expo环境执行命令:
npx expo install @react-native-async-storage/async-storage - 修改Firebase初始化配置,显式指定Auth使用独立AsyncStorage作为持久化存储,替换默认调用逻辑。修改
../firebase文件的初始化代码:
import { initializeApp } from "firebase/app"; // 替换原来的getAuth导入,用initializeAuth配合持久化配置 import { initializeAuth, getReactNativePersistence } from "firebase/auth"; import AsyncStorage from "@react-native-async-storage/async-storage"; // 替换为你自己的Firebase项目配置 const firebaseConfig = { apiKey: "xxx", authDomain: "xxx", projectId: "xxx", storageBucket: "xxx", messagingSenderId: "xxx", appId: "xxx" }; const app = initializeApp(firebaseConfig); // 初始化Auth时指定持久化引擎 export const auth = initializeAuth(app, { persistence: getReactNativePersistence(AsyncStorage) });
配置完成后重新启动项目,警告就会消失,同时登录态持久化功能也能正常工作。
内容的提问来源于stack exchange,提问作者John George
相关产品推荐
相关产品推荐

