我已经创建了一条受保护的路线,并且可以正常工作。结果是,每当我手动键入url时,它都不会进入仪表板,因为它未经身份验证,因此您需要先单击Login Button,这样它将直接转到Dashboard,但是问题是当我单击Login按钮并且已经在仪表板并刷新页面,它会再次返回登录页面。
这是我的身份验证代码:
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
我的代码有问题吗?预期的结果是当我单击登录并定向在仪表板中时,每当我单击刷新时,它将保留在仪表板中。谢谢
答案 0 :(得分:0)
您会在刷新时看到状态重置,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();
答案 1 :(得分:0)
每次刷新由new Auth()
创建的页面this.authenticated = false;
对象时,Routes组件都会呈现Login组件(auth.isAuthenticated() === false)
。为了达到目的,您只需要保留Auth.authenticated
值,然后在Auth构造函数中检查其值是否持久,然后重新保存其持久值。例如,您可以简单地使用本地存储来存储您的Auth状态。