firebase auth在signInWithPhoneNumber上返回null

时间:2018-09-12 09:45:03

标签: firebase react-native firebase-authentication

我正在尝试使用Firebase signInWithPhoneNumber()方法登录电话号码。在其中我检查了用户身份验证状态是否已更改。如果用户身份更改,则登录并重定向到主页。但是我得到的身份验证为空

 onLoginBtnClicked() {

        const { contact, password } = this.props;
        const error =  Validator('password', password) ||  Validator('contact', contact);

        if (error !== null) {
          Alert.alert(error);
        } else {
              console.log('else');
            // this.props.loginUser({ contact, password});
            const mobileNo = '+91'+contact;
            firebase.auth().signInWithPhoneNumber(mobileNo)
            .then(data => console.log(data),
              firebase.auth().onAuthStateChanged((user) => {
                console.log('user'+user);
                  if (user && !CurrentUser.isFirstTimeUser) {

                    const userRef = firebase.database().ref(`/users/`);

                    userRef.on("value", (snapshot) => {

                      console.log(snapshot.val());
                      snapshot.forEach(function(item) {
                        var itemVal = item.val();
                        if(itemVal.mobile == contact){
                                  NavigationService.navigate('Home');
                        }

                      });

                    }, (errorObject) => {
                      console.log("The read failed: " + errorObject.code);
                    });
                    //NavigationService.navigate('Home');
                  }
                })
            )
            .catch(error => console(error.message) );


        }
    }

1 个答案:

答案 0 :(得分:2)

这里有两件事要注意

  • onAuthStateChanged是一个监听器,用于监听用户身份验证更改
  • signInWithPhoneNumber将代码发送到用户的手机,您必须确认以验证用户身份。

您需要在组件的反应生命周期中为其添加侦听器,而在其卸载后将其删除

componentDidMount() {
    this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({ user: user.toJSON() });
      } else {
        // Reset the state since the user has been logged out
      }
    });
  }

  componentWillUnmount() {
     if (this.unsubscribe) this.unsubscribe();
  }

  // Send Message here
  firebase.auth().signInWithPhoneNumber(mobileNo)
     .then(confirmResult => this.setState({ confirmResult })
     .catch(error => // handle the error here)

  // Authenticate User typed Code here
  const { userCode, confirmResult } = this.state;
  if (confirmResult && userCode.length > 0) {
   confirmResult.confirm(codeInput)
    .then((user) => {
      // handle user confirmation here or in the listener
    })
    .catch(error => // handle the error here)
  }