一个非常简单的应用程序。在/
路径上,我想在登录时呈现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;
答案 0 :(得分:1)
以下是发生的事情:
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
}
}