安装组件时,我想呈现登录屏幕或应用程序,具体取决于用户登录的情况.但是,每次刷新时,用户都会注销.我如何让他们登录? 应用组件: firebase.initializeApp(config); //init the firebase app...cla
应用组件:
firebase.initializeApp(config); //init the firebase app... class App extends Component {//this component renders when the page loads constructor(props){ super(props); this.state = {user: firebase.auth().currentUser};//current user } render(){ if (this.state.user) {//if you are logged in return ( <Application/> ); } else {//if you are not logged in return ( <Authentication/> ); } } }
这是我用来登录用户的方法(工作正常):
let email = "some"; let password = "thing"; const auth = firebase.auth(); const promise = auth.signInWithEmailAndPassword(email, password);用户的令牌会自动持久保存到本地存储,并在加载页面时读取.这意味着重新加载页面时,应再次自动对用户进行身份验证.
最可能的问题是您的代码未检测到此身份验证,因为您的App构造函数在Firebase重新加载并验证用户凭据之前运行.要解决此问题,您需要listen for the (asynchronous) onAuthStateChanged()
event,而不是同步获取值.
constructor(props){ super(props); firebase.auth().onAuthStateChanged(function(user) { this.setState({ user: user }); }); }