[英]React js - Protected Routes
我创建了一个受保护的路线并且它有效。 结果是每当我手动键入 url 时,它不会在仪表板内显示 go,因为它未经过身份验证,因此您需要先单击“登录”按钮,以便它直接进入仪表板,但问题是当我单击“登录”按钮并且已经在仪表板并刷新页面,它再次返回登录页面。
这是我的身份验证代码:
class Auth {
constructor() {
this.authenticated = false;
}
login(cb) {
this.authenticated = true;
cb();
}
logout(cb) {
this.authenticated = false;
cb();
}
isAuthenticated() {
return this.authenticated;
}
}
export default new Auth();
对于我的routes.js
import React from 'react'
import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'
import Login from './login.js'
import Dashboard from './dashboard.js'
import auth from "./auth.js";
export const ProtectedRoute = ({
component: Component,
...rest
}) => {
return (
<Route
{...rest}
render={props => {
if (auth.isAuthenticated()) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: "/",
state: {
from: props.location
}
}}
/>
);
}
}}
/>
);
};
const Routes = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Login} />
<ProtectedRoute path="/dashboard" component={Dashboard} />
</Switch>
</BrowserRouter>
)
export default Routes
我的代码有问题吗? 预期结果是当我单击登录并在仪表板中定向时,每当我单击刷新时它都会保留在仪表板中。 谢谢
您在刷新时看到您的 state 重置并且this.authenticated
变为false
将您的 state 存储在localStorage
中
在设置 state 时设置localStorage
。
class Auth {
constructor() {
this.authenticated = false;
}
componentDidMount(){
this.setState( { authenticated: JSON.parse(localStorage.getItem("auth")) } )
}
login(cb) {
this.authenticated = true;
localStorage.setItem("auth","true")
cb();
}
logout(cb) {
this.authenticated = false;
cb();
}
isAuthenticated() {
return this.authenticated;
}
}
export default new Auth();
每次刷新页面时, new Auth()
object created with this.authenticated = false;
所以你的路由组件渲染登录组件(auth.isAuthenticated() === false)
。 为了达到你的观点,你只需要保留你的Auth.authenticated
值,然后在你的 Auth 构造函数中检查它是否持久并重新水化它的持久值。 例如,您可以简单地使用本地存储来存储您的 Auth state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.