【问题标题】:React Application Will "Flash" Default Page Before Redirecting An Authenticated UserReact 应用程序将在重定向经过身份验证的用户之前“闪烁”默认页面
【发布时间】:2021-12-13 22:49:47
【问题描述】:

我的 React 应用程序在加载时会检查是否有经过身份验证的用户。如果有,则经过身份验证的用户将被重定向到他们的“仪表板”页面。但是,当这种情况发生时,应用程序会在重定向之前短暂闪烁/闪烁未经身份验证的登录页面。有没有办法防止这种情况发生?

import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'
import { SignUp } from './SignUp'
import { Login } from './Login'
import { Dashboard } from './Dashboard'
import { Welcome } from './Welcome.js'
import { AuthContextProvider, useAuthState } from './firebase'

const AuthenticatedRoute = ({ component: C, ...props }) => {
  const { isAuthenticated } = useAuthState()
  console.log(`AuthenticatedRoute: ${isAuthenticated}`)
  return (
    <Route
      {...props}
      render={routeProps =>
        isAuthenticated ? <C {...routeProps} /> : <Redirect to="/welcome" />
      }
    />
  )
}

const UnauthenticatedRoute = ({ component: C, ...props }) => {
  const { isAuthenticated } = useAuthState()
  console.log(`UnauthenticatedRoute: ${isAuthenticated}`)
  return (
    <Route
      {...props}
      render={routeProps =>
        !isAuthenticated ? <C {...routeProps} /> : <Redirect to="/" />
      }
    />
  )
}

function App() {
  return (
    <AuthContextProvider>
      <Router>
        <div></div>
        <AuthenticatedRoute exact path="/" component={Dashboard} />
        <UnauthenticatedRoute exact path="/signup" component={SignUp} />
        <UnauthenticatedRoute exact path="/signin" component={Login} />
        <UnauthenticatedRoute exact path="/welcome" component={Welcome} />
      </Router>
    </AuthContextProvider>
  )
}

export default App

【问题讨论】:

    标签: reactjs redirect react-router


    【解决方案1】:

    这是因为当 firebase 请求得到响应时,isAuthenticated 为 false。

    您可以在实际返回语句之前使用 useAuthState isLoading 标志返回 null 或空 div,因此加载的第一页是空白的。

    if (isLoading) return null
    // Then your actual return statement.
    

    当 isLoading 变为 false 时,isAuthenticated 标志将直接解析为最终值。

    试一试,告诉我它是否有效。

    【讨论】:

    • 谢谢!我必须将它与 useState 一起使用,对吗?像这样开始它? const [isLoading, setIsLoading] = useState(false);
    • 虽然我不使用 firebase,但阅读文档似乎 useAuthState 除了返回 isAuthenticated 之外还返回 isLoading,所以你只需要解构两者。
    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2021-04-01
    • 2011-12-03
    • 2019-04-25
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多