TypeError:无法读取null的属性"uid" [英] TypeError: Cannot read property 'uid' of null
问题描述
我正在尝试使用Firebase在我的应用程序中使用电话号码登录,但登录过程遇到问题.我无法使用Firebase中的电话号码登录,但是如果我使用电话号码注册并重定向到主页,则它可以正常工作.我使用相同的方法登录,但是遇到类似TypeError: Cannot read property 'uid' of null
的问题,但是我成功获取了所有控制台值.我不知道这是什么问题.但是该错误会重复显示3次,
I am trying to log in with a phone number in my app with firebase but I am facing issue with the login process. I'm not able to login with a phone number in firebase but if I register with a phone number and redirect to the homepage it's working properly. I am using the same method to login, but I got the issue like TypeError: Cannot read property 'uid' of null
but I an successfully getting all the console values. I don't know what is being the issue here. But that error is displaying in 3 times repeatedly,
这是我的代码:
renderLoginButton() {
if (this.props.loading) {
return (
<Spinner size="large" />
);
}
return (
<Button
style={{ alignSelf: 'flex-start' }}
onPress={this.onLoginBtnClicked.bind(this)}
>
Login
</Button>
);
}
onLoginBtnClicked(){
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(confirmResult =>
console.log(confirmResult),
curr = firebase.auth(),
console.log("curr"+JSON.stringify(curr)),
this.setState({ data: curr}),
NavigationService.navigate('Home')
)
.catch(error => console(error.message) );
}
}
CustomDrawerComponent.js
CustomDrawerComponent.js
import React, { Component } from 'react';
import { View, Image, Text } from 'react-native';
import { DrawerItems } from 'react-navigation';
import { connect } from 'react-redux';
import { fetchUserDetails } from '../actions';
class CustomDrawerContentComponent extends Component {
state = {
uri: '',
isfailed: ''
}
componentWillMount() {
this.props.fetchUserDetails();
}
componentWillReceiveProps(nextProps) {
let uri = '';
if (nextProps.ProfilePic !== '') {
uri = nextProps.ProfilePic;
this.setState({ uri, isfailed: false });
} else {
uri = '../images/ic_person_24px.png';
this.setState({ uri, isfailed: true });
}
this.setState({ uri });
}
renderProfileImage() {
if (!this.state.isfailed) {
return (
<Image
style={styles.profileImageStyle}
source={{ uri: (this.state.uri) }}
/>
);
}
return (
<Image
style={styles.profileImageStyle}
source={require('../images/ic_person_24px.png')}
/>
);
}
render() {
console.log('Profile Pic :: ', this.props.ProfilePic);
return (
<View style={styles.container}>
{this.renderProfileImage()}
<Text style={styles.textStyle}>
{this.props.name} - {this.props.category}
</Text>
<DrawerItems {...this.props} />
</View>
);
}
}
const styles = {
container: {
flex: 1,
paddingLeft: 10
},
textStyle: {
fontSize: 14,
textAlign: 'left',
color: '#000000'
},
profileImageStyle: {
alignSelf: 'flex-start',
marginTop: 16,
padding: 10,
width: 40,
height: 40,
borderRadius: 75
}
};
const mapStateToProps = state => {
const { userprofile } = state;
return userprofile;
};
export default connect(mapStateToProps, { fetchUserDetails })(CustomDrawerContentComponent);
callStack:
callStack:
推荐答案
为什么user
返回为undefined
(甚至是null
)?
Why does the user
return as undefined
(or even null
)?
您知道有一个已登录用户,您刚刚登录,哎呀,您甚至可以在chrome开发工具中看到该用户对象.
You know there’s a logged in user, you just logged in, heck, you can even see the user object in chrome dev tools.
然后为什么它仍返回未定义?有一个直接的答案.
Then why is it still returning undefined? There’s a straight answer to it.
您要获取用户对象之前,该对象已可以使用.
You’re fetching the user object BEFORE that object is ready to be used.
现在,由于几种不同的原因可能会发生这种情况,但是如果您遵循这2条规则",您将不会再看到该错误.
Now, this can happen because of several different reasons, but if you follow this 2 "rules" you won’t see that error again.
规则1:将其移出constructor()
Rule #1: Move it out of the constructor()
当您遇到类似情况时:
constructor(){
this.userId = firebase.auth().currentUser.uid
}
在页面加载时间的一半以上,构造函数将尝试在用户准备就绪之前获取用户,由于页面未完全加载,应用程序阻止了该用户,因此您将尝试访问尚未存在的属性的uid.
Over half of the time that page loads, the constructor is going to try to get the user before the user is ready, the app is blocking it because the page isn’t fully loaded, so you’re going to be trying to access uid of a property that just isn’t there yet.
页面完全加载后,您现在可以致电获取currentUser.uid
When you get your page fully loaded, you can now call to get the currentUser.uid
规则2:使其可观察
您可以采用另一种方法,即我们刚才进行的上一次Firebase调用:firebase.auth().currentUser是同步的.我们可以通过订阅auth observable使其异步.
There’s another approach you can take, that previous Firebase call we just made: firebase.auth().currentUser is synchronous. We can make it asynchronous by subscribing to the auth observable instead.
/**
* When the App component mounts, we listen for any authentication
* state changes in Firebase.
* Once subscribed, the 'user' parameter will either be null
* (logged out) or an Object (logged in)
*/
componentDidMount() {
this.authSubscription = firebase.auth().onAuthStateChanged((user) => {
this.setState({
loading: false,
user,
});
});
}
/**
* Don't forget to stop listening for authentication state changes
* when the component unmounts.
*/
componentWillUnmount() {
this.authSubscription();
}
render() {
// The application is initialising
if (this.state.loading) return null;
// The user is an Object, so they're logged in
if (this.state.user) return <LoggedIn />;
// The user is null, so they're logged out
return <LoggedOut />;
}
}
源文章:为什么Firebase在获取uid
时为何返回undefined
?
Source article: Why does Firebase return undefined
when fetching the uid
?
关于React Native的一个很好的教程将在这里:在React Native上开始使用Firebase身份验证 既然您的代码显示的不是很多,我希望您对问题进行更新以显示更多的代码,以便我可以浏览一下.
A good tutorial for React Native will be here: Getting started with Firebase Authentication on React Native Since, your code did not show much, I hope you make an update to your question to show more code, so I might be able to look through.
这篇关于TypeError:无法读取null的属性"uid"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!