我有一个具有动态渲染功能的应用程序。用户登录后我想加载内容。当他们按下我的欢迎组件中的登录按钮时,我的 SignUpPressed 函数将执行:
signUpPressed = () => {
console.log("signUpPressed called")
let email = this.state.email
let password = this.state.password
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code
var errorMessage = error.message
console.log(errorCode)
console.log(errorMessage)
})
var user = firebase.auth().currentUser;
if (user) {
console.log("user is" + user)
this.props.handler(true)
}
}
但是,在从应用程序组件调用传递给此欢迎组件的处理程序之前,我必须按两次它。我尝试做 .then 或 .finally 但无法弄清楚。我的 App.js 代码如下所示:
class App extends Component {
state = {
loggedIn: false
}
handler = (val) => {
this.setState({
loggedIn: val
})
}
我该怎么办。
最佳答案
您需要使用方法 onAuthStateChanged
检查用户,如官方文档中的以下示例所示:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
监听器本身用于检测变化;您可以根据用户对象从内部定义登录/注销行为。
当没有用户时,user将为null,因此会发生你的登出情况;
当有用户时,该对象将是真实的,触发登录案例,其中包含很多属性,例如 user.email 等 - 有关更多信息,请参阅文档。
您可以直接在处理程序中进行检查,或者使用处理程序来标记其自身外部的某些内容,然后进行检查。
https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user0
关于reactjs - 检查 Firebase 登录是否成功 React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447612/