首页 > 解决方案 > 使用 React Native Expo 进行 Firebase 电话身份验证

问题描述

所以我一直在尝试在我的 react native 项目中实现 firebase phone auth。我遵循了下面链接的这个很棒的教程,但是在将确认部分更改为不同的页面而不是电话号码输入和代码输入都在同一页面上时遇到了问题。我收到一条错误消息,指出未找到 verifyId,因为它在上一页中被调用。

教程链接

如果有人能帮忙,那就太好了。

谢谢

  const const Login  = () => {
  const navigation =useNavigation();
  const [phoneNumber, setPhoneNumber] = useState();

  const [verificationId, setVerificationId] = useState(null);
  const recaptchaVerifier = useRef(null);




    const sendVerification  = () => {
       try {
    const phoneProvider = new firebase.auth.PhoneAuthProvider();
    phoneProvider
   .verifyPhoneNumber(phoneNumber, recaptchaVerifier.current)
   .then(setVerificationId);
     } catch (error) {
   alert(error);
     }
     navigation.navigate('OTPScreen', { verificationId: 
   verificationId})


     };
    return(
   

一次性密码屏幕

const const OTPScreen  = () => {

const verificationId = props.route.params.verificationId
 const [code, setCode] = useState('');


const confirmCode = () => {
  const credential = 
  firebase.auth.PhoneAuthProvider.credential(
    verificationId,
    code
  );
  firebase
    .auth()
    .signInWithCredential(credential)
    .then((result) => {
      console.log(result); 
      navigation.navigate('Home')  
        
    });
    

    };
   return(
   

标签: javascriptfirebasereact-nativefirebase-authentication

解决方案


我已经实施了两种可能的解决方案

  1. 将您的确认对象作为参数传递到新屏幕,然后将其用于 OTP 确认。
  2. 您还可以将此确认对象保存在 redux 等全局存储中。

对于解决方案 1

const [confirm, setConfirm] = useState(null);


  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
    setConfirm(confirmation);
  }

然后导航到您的 otp 屏幕

navigation.navigate('otpScreen', {confirm: confirm})

在您的 otpScreen 上,将确认对象作为参数(无论您使用的是什么,都对功能或类组件使用适当的语法)然后

const confirm = props.route.params.confirm

async function confirmCode() {
    try {
      await confirm.confirm(code);
    } catch (error) {
      console.log('Invalid code.');
    }
  }

推荐阅读