为什么Firebase用户在刷新时不再进行身份验证?

时间:2018-01-30 20:23:33

标签: javascript reactjs firebase react-router firebase-authentication

一个非常简单的应用程序。在/路径上,我想在登录时呈现Home,如果没有登录,则Introduction。登录登录页面,如果我是console.log(firebase.auth() .currentUser)它显示所有数据,并在/上正确呈现Home。所以,当仍然在/路径时,会发生一些奇怪的事情;当我刷新页面时,我们不再登录并呈现Introduction。但是,当我点击链接<li><Link to='/'>Home</Link></li>时,Home组件正确呈现,我们又重新登录。为什么会这样?

import React, { Component } from 'react';
import {BrowserRouter as Router, Route, Switch, Link, Redirect} from 'react-router-dom';
import firebase from './firebase'

import Home from './containers/home'
import Login from './containers/login'
import Register from './containers/register'
import Dashboard from './containers/dashboard'

const Protected = ({component: Component, ...rest}) => (
  <Route {...rest} render={(props) => {
    if(firebase.auth().currentUser) 
      return <Component {...props} />
     else 
      return <Redirect to='/register' />

  }} />
)

const Introduction = props => ( <h1>hello</h1>)

class App extends Component {


  render() {
    return (
      <Router>
        <React.Fragment>
          <ul>
            <li><Link to='/'>Home</Link></li>
            <li><Link to='/register'>Register</Link></li>
            <li><Link to='/login'>login</Link></li>
            <li><Link to='/dashboard'>dashboard</Link></li>
          </ul>
          <Switch>
            <Route path='/' exact render={(props) => {
              if(firebase.auth().currentUser) 
                return <Home {...props} />
              else
                return <Introduction {...props} />
              }
            } />
            <Route path='/register' exact component={Register} />
            <Route path='/login' component={Login} />
            <Protected path='/dashboard' component={Dashboard} />
          </Switch>
        </React.Fragment>
      </Router>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

以下是发生的事情:

  • 网页加载
  • Firebase会启动检查用户是否经过身份验证的请求
  • 应用呈现,currentUser为空
  • 身份验证状态发生变化,但应用程序不会重新呈现

应用程序需要侦听身份验证状态的更改并相应地执行重新呈现。 https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

class App extends React.Component {
  state = {
    currentUser: null
  }

  componentDidMount() {
    this.unsubscribe = firebase.auth().onAuthStateChanged(currentUser => {
      this.setState({ currentUser })
    })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    // use this.state.currentUser
  }
}