首页 > 解决方案 > 当用户未通过身份验证时反应闪烁的私有路由

问题描述

react-router-dom用来保护整个应用程序。所有路由都受到 ProtectedRoute 组件的保护(参见下面的代码),如果用户未登录,该组件将重定向到外部 url,即单点登录 (SSO) 页面。

问题:

当用户转到“/home”时,他们会在被重定向到“external-login-page.com/”(登录页面)之前对受保护的路由有一个简短的了解(“闪光”)。如何避免闪烁,以便用户只看到登录页面?

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  isAuthenticated,
  ...rest
}) => {
  if (!isAuthenticated) { // redirect if not logged in
    return (
      <Route
        component={() => {
          window.location.href = 'http://external-login-page.com/';
          return null;
        }}
      />
    );
  } else {
    return <Route {...rest} />;
  }
};

标签: reactjsreact-routerreact-router-dom

解决方案


window.location.href可以提前调用以防止闪烁。同样在您的特定情况下,您可能想要的是在用户未通过身份验证时根本不呈现任何内容。

代码可能如下所示:

export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  isAuthenticated,
  ...rest
}) => {
  if (!isAuthenticated) { // redirect if not logged in
    window.location.href = 'http://external-login-page.com/';
    return null;
  } else {
    return <Route {...rest} />;
  }
};

推荐阅读