我尝试在loadingScreen上启动我的应用程序,在该屏幕上检查是否有任何与firebase的会话, 这是我尝试了很多版本的代码,但是没有任何效果,我认为这是对JS作用域缺乏了解
版本2
//importing
import {f,fAuth} from '../../config'
class Loading extends React.Component {
componentDidMount(){
f.auth().onAuthStateChanged((user)=>{console.log(user);this.nav(user) })
}
nav(user)
{
console.log(user)
if (user===null){
console.log(user)
// to login page
this.props.navigation.navigate('auth')
}
else{
console.log(user)
// to home page
this.props.navigation.navigate('main')
}
}
}
版本1
componentDidMount(){
f.auth().onAuthStateChanged(user=>{th.props.navigation.navigate(user ?'main':'auth')})
}
在配置文件中
import firebase from 'firebase';
var firebaseConfig = {
apiKey: "AIzaSyDYcY1wXll4JI3Gb-qokG6F6KQZB5zzrkg",
authDomain: "insta-12594.firebaseapp.com",
databaseURL: "https://insta-12594.firebaseio.com",
projectId: "insta-12594",
storageBucket: "insta-12594.appspot.com",
messagingSenderId: "898455527488",
appId: "1:898455527488:web:6a749552a9401905de0eec5"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig)
export const f = firebase;
export const fDb= firebase.database()
export const fAuth= firebase.auth()
答案 0 :(得分:0)
您可以做类似的事情
class Loading extends React.Component {
componentDidMount(){
this.authSubscriber = f.auth().onAuthStateChanged(this.authListener)
}
componentWillUnmount() {
if (this.authSubscriber) {
this.authSubscriber();
}
}
authListener = async user => {
if (!user) {
this.props.navigation.navigate('auth');
} else {
this.props.navigation.navigate('main');
}
};
render(){
return (
<View>
<Text>Loading...</Text>
</View>
)
}
}
答案 1 :(得分:0)
在多次尝试使用state
之后,我发现状态不会立即更新,例如:
state={
userState:'ha'
}
componentDidMount(){
console.log('up',this.state.userState)
f.auth().onAuthStateChanged(user=>this.setState({ userState: 'hi' }, () =>
console.log('middle',this.state.userState)))
console.log('bottom',this.state.userState)
}
输出将是:
up ha
down ha
middle hi
知道这一事实后,我尝试在this.setState
的回调中调用该函数
像这样:
state={
userState:'ha'
}
componentDidMount(){
f.auth().onAuthStateChanged(user=>this.setState({ userState: user }, () =>
this.props.navigation.navigate(this.state.userState===null?'auth':'main')))
}