React Native Expo运行报ReferenceError: Can't find variable: email求助
问题根因
你当前的错误是变量作用域不匹配导致的:
email和password是你在RegisterScreen函数组件内部定义的state变量,仅在组件的函数作用域内可以被访问- 你把
register函数定义在了RegisterScreen组件的外层,外层作用域不存在email、password这两个变量,调用createUserWithEmailAndPassword时读取不到对应变量,就抛出了引用错误。
修复方案
把register函数挪到RegisterScreen组件内部即可,调整后的代码参考:
import { KeyboardAvoidingView, StyleSheet, View } from 'react-native'; import React, { useState } from 'react'; import { StatusBar } from 'expo-status-bar'; import { Button, Input, Text } from 'react-native-elements'; import { auth } from '../firebase'; const RegisterScreen = ({navigation}) => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [imageUrl, setImageUrl] = useState(""); // 把register函数移到组件内部,就可以正常访问内部的state变量 const register = () => { auth .createUserWithEmailAndPassword(email, password) .then((authUser) => {}) .catch((error) => alert(error.message)); }; // 下方剩余的组件渲染逻辑保持不变 }
额外可选优化
如果你需要把register作为公共方法复用,可以改为参数传递的形式,避免依赖组件内部作用域:
// 抽离的公共方法 const register = (email, password) => { return auth .createUserWithEmailAndPassword(email, password) .then((authUser) => {}) .catch((error) => alert(error.message)); }; // 组件内调用时传入对应state const RegisterScreen = ({navigation}) => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [imageUrl, setImageUrl] = useState(""); // 调用时传参 const handleRegister = () => register(email, password) }
内容的提问来源于stack exchange,提问作者Chee Thong
相关产品推荐
相关产品推荐

