在我的App.js中,我初始化firebase并检查:是否是否有用户,它转到MainPage,否则转到StartPage (stackNavigator) 。而且我想获取用户(firebase.auth()。currentUser)的电子邮件,以将其显示在MainPage上。但是它返回 RED ERROR PAGE ,其中 NULL不是对象
在我在AndroidStudio上进行编程之前,我是第一次使用Firebase进行本机响应(因此我没有更多的经验)。希望您能帮助您分享经验
下面提供了源代码。
我也在App.js而不是Login.js上写了user.sendEmailVerification()
,因为它无法在LoginPage上吸引用户
App.js
import React from 'react';
import { createStackNavigator } from 'react-navigation';
import firebase from 'firebase';
import StartPage from './components/utils/StartPage';
import MainPage from './components/employer/MainPage ';
firebase.initializeApp({
apiKey: "AIxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxx"
});
const AppStackNavigator = createStackNavigator(
{
MainPage: MainPage ,
Start: StartPage,
Login: Login,
},
{
initialRouteName: 'MainPage',
}
);
const StartNavigator = createStackNavigator(
{
MainPage : MainPage ,
Start: StartPage,
Login: Login,
},
{
initialRouteName: 'Start',
}
);
export default class App extends React.Component {
state = {
user: {},
};
componentDidMount() {
this.authListener();
}
authListener() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
if (user.emailVerified) {
this.setState({ user });
} else {
user.sendEmailVerification();
this.setState({ user });
}
} else {
this.setState({ user: null });
}
});
}
render() {
return (
{this.state.user ? <AppStackNavigator /> : <StartNavigator />}
)
}
}
HomePage.js
import React from 'react';
import { ScrollView, FlatList, View, Text } from 'react-native';
import { StyleSheet, TouchableOpacity, Image } from 'react-native';
import firebase from 'firebase';
export default class HomePage extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
let headerTitle = 'Home Page';
let headerLeft = null;
let headerRight = (
<TouchableOpacity
style={styles.headerButton}
onPress={() => {
params.onSignout();
}}>
<Image
source={require('./../../assets/logout.png')}
style={styles.headerImageStylee}
/>
</TouchableOpacity>
);
return {
headerTitle, headerLeft, headerRight,
};
};
user = firebase.auth().currentUser;
onSignout = () => {
Alert.alert('', 'Log out?', [
{ text: 'Yes', onPress: () => console.log('canceled') },
{
text: 'No',
onPress: () => firebase.auth().signOut(),
},
]);
};
render() {
return (
<View style={styles.container}>
<Text>`${this.user.email}`</Text>
</View>
);
}
}
P.S。我使用下面的代码发送sendmail验证,但是它没有用,所以我将其复制到App.js
Login.js的一部分-> 注册函数
register = e => {
e.preventDefault();
this.state.password === this.state.rPassword
? firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(user){
user.sendEmailVerification();
}).catch(error => {
Alert.alert('', error.message, [{ text: 'Ок' }]);
})
: Alert.alert('', 'Passwords not match', [{ text: 'Ок' }]);
};