我正在开发一个反应原生应用程序与Firebase身份验证。但是当我成功登录时,导航显示出一些问题,比如,未定义不是一个对象(评估this.props.navigation)。我尝试了很多方法,但都没用。伙计们,请帮帮我。
import React from "react";
import {
Text,
View,
Image,
TouchableOpacity,
AsyncStorage,
TextInput
} from "react-native";
import { styles } from "./Css";
import { KeyboardAvoidingView } from "react-native";
import { RkTextInput, RkButton } from "react-native-ui-kitten";
import { Actions } from "react-native-router-flux";
import { Icon } from "react-native-elements";
import * as firebase from "firebase";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
userId: "",
errorMessage: null,
};
}
componentDidMount() {
this._loadInitialState().done();
}
_loadInitialState = async () => {
var value = await AsyncStorage.getItem("user");
if (value !== null) {
this.props.navigation.navigate("NewHome")
}
};
handleLogin = (email, password) => {
if(this.state.email.length<1){
alert("Enter an Email");
return;
}
if (this.state.email.includes("@")==false){
alert("Use an email as Username");
return;
}
if(this.state.password.length<6){
alert("please enter correct password")
return;
}
//alert(firebase.auth().currentUser.uid)
firebase.auth().signInWithEmailAndPassword(email, password).then(function(user){
if(user){
this.props.navigation.navigate("NewHome"), //problem
//--------------------------Async Test--------------------------
AsyncStorage.setItem("user", firebase.auth().currentUser.uid)
//--------------------------------------------------------------
}else{
}
}
)
.catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
alert("Wrong password.");
return;
} else {
alert(errorMessage);
return;
}
console.log(error);
});
};
这个
不再指向你的React类了。
解决方案可以使用箭头函数:
firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {...}
或者,在firebase回调中使用它之前,必须将其保存在函数中。
let props = { ...this.props };
在回调函数中,将其用于导航:
props.navigation.navigate('NewHome');