reactjs - 当用户未通过身份验证时反应闪烁的私有路由
问题描述
我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} />;
}
};
解决方案
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} />;
}
};
推荐阅读
- mysql - 检查与您的 MySQL 服务器版本相对应的手册,以了解在 ''execute_transaction'(IN sql_text VARCHAR(8000)) 附近使用的正确语法
- android - 如何从 adb shell 触发“Ok google”?
- c# - Application.DoEvents() 是多任务处理的一种形式吗?
- vba - 在括号中查找文本并更改某些匹配项
- java - p:calendar 时间滑块丢失小时和分钟
- java - 如何在 executeQuery 方法中编写 sql 查询?
- ios - 取消 iOS 麦克风回声消除和噪音抑制
- python - 为什么 Python 中的“r”和 .read() 会出现不同的结果?
- testing - Rust 恐慌单元测试 - 匹配错误消息的细节
- angular - BabylonJS Canvas 在 Angular 6 中是空白的