我正在使用 Firebase.auth() 通过 Google Firebase 对登录进行身份验证,然后我检索 UID 并将其发送到我的 Redux 商店。除非我导航到下一页然后返回登录页面,否则 UID 不会发送到商店。看来我的操作顺序已关闭,如何在不必重新登录/刷新页面的情况下在 Redux 商店中获取 UID。
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
id: ''
}
}
id (value) {
this.props.id(value);
}
handleLogin = (load) => {
const { email, password } = this.state
Firebase.auth()
.signInWithEmailAndPassword(email, password)
.then(async cred => {
return db.collection('users').doc(cred.user.uid).set({
test: 'test'
})
})
.then(() => this.props.navigation.navigate('AddProfiles'))
.catch(error => console.log(error))
const currentUser = firebase.auth().currentUser;
const userId = currentUser["uid"];
this.setState({
id: userId
})
this.props.id(this.state.id);
}
<TouchableOpacity style={styles.signupbutton}>
<Button
color='white'
title="Log in"
onPress={(payload) => this.handleLogin()}
/>
</TouchableOpacity>
const mapStateToProps = (state) => {
return {
counter: state.counter,
value: state.id
};
}
const mapDispatchToProps = dispatch => {
return {
id: (value) => dispatch({ type: 'id', payload: value })
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Home)
现在,以该行开头的代码在完成之前const currentUser
运行,因为它是一个异步函数。它在刷新时起作用的原因是在这一点上,具有价值,所以signInWithEmailAndPassword
signInWithEmailAndPassword
firebase.auth().currentUser
您可以将代码移到then
块内,使其仅在函数完成时运行。它看起来像这样(未经测试,因为我没有你的其余代码):
handleLogin = (load) => {
const { email, password } = this.state
Firebase.auth()
.signInWithEmailAndPassword(email, password)
.then(async cred => {
this.setState({
id: cred.user.uid
})
this.props.id(cred.user.id);
return db.collection('users').doc(cred.user.uid).set({
test: 'test'
})
})
.then(() => this.props.navigation.navigate('AddProfiles'))
.catch(error => console.log(error))
}
请注意,setState
是同时同步的,因此调用this.props.id(this.state.id);
之后setState
很可能会失败在第一次运行。
虽然以上应该解决眼前的问题,但我建议onAuthStateChanged
:https : //firebase.google.com/docs/auth/web/start#set_an_authentication_state_observer_and_get_user_data
这样,您可以登录并根据其值设置 Redux 状态,或者在用户刚刚返回页面时运行相同的代码来设置 Redux 值。它可能会导致比将所有东西都捆绑在一起更强大的情况signInWithEmailAndPassword
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句