一个非常简单的应用程序。在 /
我要渲染的路径 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;
最佳答案
这是发生了什么:
- 网页加载
- Firebase 发起请求以检查用户是否已通过身份验证
- 应用呈现,
currentUser
为 null - 身份验证状态发生变化,但应用不会重新呈现
应用程序需要监听身份验证状态的变化并相应地执行重新渲染。 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
}
}
关于javascript - 为什么刷新时不再对 Firebase 用户进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48529910/