首页 > 解决方案 > 反应原生 TypeError:无法读取未定义的属性“导航”

问题描述

我正在使用FacebookAuthProviderby firebase 从我的平台登录我的用户。

我在带有firestore的expo中使用react native,它工作正常,直到我尝试添加一些检查以在登录后将用户重定向到正确的屏幕。有两个不同的角色(管理员用户)在登录后必须分开。

if (/* user is administrator */) {
  this.props.navigation.navigate('Admin');
} else {
  this.props.navigation.navigate('Main');
}

添加此方法以按角色分隔用户后,出现此错误:

反应原生 TypeError:无法读取未定义的属性“导航”

稍后我将添加更多详细信息(一旦我学会了如何从我的语言环境机器上 grep 日志文件等)。

为了更好地理解,我将整个代码放在这里(抱歉缩进会降低可读性):

const auth = firebase.auth();
const firebaseUser = '';
const usersRef = firebase.firestore().collection('users');

async handleFacebookButton() {

const { type, token,  } = await Facebook.logInWithReadPermissionsAsync(FACEBOOK_APP_ID, {
  permissions: ['public_profile', 'email']
});
if (type === 'success') {
  //Firebase credential is created with the Facebook access token.
  const credential = firebase.auth.FacebookAuthProvider.credential(token);
  auth.signInAndRetrieveDataWithCredential(credential)
  .then(function(userCredential) {
    newUserCheck = userCredential.additionalUserInfo.isNewUser;
    console.log('newUserCheck = ', newUserCheck)
  });
  this.setState({loggedIn: "You are signed in"})
  this.setState({signedIn: true})
  console.log('you are signed in');


firebase.auth().onAuthStateChanged(function(user) {
if (user) {

  firebaseUser = {name: user.displayName, uid: user.uid, email: user.email}
  console.log(firebaseUser.name, ' and ',  firebaseUser.uid);

    var existingRef = usersRef.doc(firebaseUser.uid);
    existingRef.get().then(function(documentSnapshot) {
      // check if user is registered
        if(documentSnapshot) {
          data = documentSnapshot.data();
          console.log('existing user exists!!');
            // check if user is an administrator
            if (data.administrator == true) {
                console.log('existing administrator exists!!');

                this.props.navigation.navigate('Admin');
              } else { this.props.navigation.navigate('Main');
                }
        }
    });

    (error => {   
      console.log('user not accessed: ', error);
    });

    //User is not yet in firebase database and needs to be saved
    // double check that user is a new user
    if (newUserCheck == true) {
    this.ref
          .doc(uid)
          .set({
            id: firebaseUser.uid,
            username: firebaseUser.name,
            email: firebaseUser.email,
          })
    this.props.navigation.navigate('ChooseRoute')
  }
}
})
}
  // If login type is not success:
  (error => {   
    this.setState({loggedIn: "Login failed: log in again"})
    this.setState({ errorMessage: error.message });

    });
}

标签: javascriptreact-nativegoogle-cloud-firestorereact-navigation

解决方案


我修好了它!!3 天后 - 这是一个绑定问题 - 经过几次不成功的尝试确定哪些是要绑定的函数的正确部分后,我将 'auth().onAuthStateChanged' 和 'documentSnapshot' 都转换为胖箭头函数并且错误消失了!!谢天谢地 ES6...!希望这对其他人有所帮助...


推荐阅读