我已经创建了一个受保护的路由,并且它起作用了。结果是,每当我手动键入的网址,它没有进入仪表板,因为它没有认证,所以你需要点击登录按钮,所以它将直接进入仪表板,但问题是,当我点击登录按钮,已经在仪表板中,并刷新页面,它再次回到登录页面。
下面是我的身份验证代码:
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
我的代码有问题吗?预期的结果是,当我单击登录并在仪表板中定向时,每当我单击刷新时,它都会留在仪表板中。谢谢
发布于 2020-02-12 13:34:11
您可以看到,在刷新时状态会重置,this.authenticated
将变为false
将你的状态存储在localStorage
中
在设置状态时设置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();
发布于 2020-02-12 13:37:59
每次刷新您的页面时,使用this.authenticated = false;
创建new Auth()
对象,以便您的路由组件呈现登录组件(auth.isAuthenticated() === false)
。为了达到你的目的,你只需要持久化你的Auth值,然后在你的Auth.authenticated
构造函数中检查它是否持久化,然后恢复它的持久值。例如,您可以简单地使用本地存储来存储您的身份验证状态。
https://stackoverflow.com/questions/60181675
复制相似问题