这是不可能的,告诉用户是否会在页面开始加载签名,还有一个工作,虽然各地。
您可以将上一个身份验证状态存储到localStorage中,以在会话之间和选项卡之间持久保存该身份验证。
然后,当页面开始加载时,您可以乐观地假设用户将自动重新登录并推迟对话框,直到您确定(即onAuthStateChanged
触发后)为止。否则,如果localStorage
键为空,则可以立即显示对话框。
页面加载后,firebase onAuthStateChanged
事件将在大约2秒钟后触发。
// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page
firebase.auth().onAuthStateChanged(user => {
if (user) {
// User just signed in, we should not display dialog next time because of firebase auto-login
localStorage.setItem('myPage.expectSignIn', '1')
} else {
// User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
localStorage.removeItem('myPage.expectSignIn')
// Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
// e.g. showDialog()
}
})
我在
React和
react-router上使用它。我将上面的代码放入
componentDidMount
我的App根组件中。那里,在渲染中,我有一些
PrivateRoutes
<Router>
<Switch>
<PrivateRoute
exact path={routes.DASHBOARD}
component={pages.Dashboard}
/>
...
这是我的PrivateRoute的实现方式:
export default function PrivateRoute(props) {
return firebase.auth().currentUser != null
? <Route {...props}/>
: localStorage.getItem('myPage.expectSignIn')
// if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
? <Spinner centered size={400}/>
: (
<>
Redirecting to sign in page.
{ location.replace(`/login?from=${props.path}`) }
</>
)
}
// Using router Redirect instead of location.replace
// <Redirect
// from={props.path}
// to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
// />