问题描述
我被困在实现私有路由的部分中
这就是我最终要实现的目标:
我想用Google登录,登录后我想进入一个私人路线页面,如果我退出了,那我就不能这样做。
对于代码部分:
class Auth {
isAuthenticated: boolean
constructor(){
this.isAuthenticated = false;
}
login(){
this.isAuthenticated= true;
}
logout(){
this.isAuthenticated = false;
}
isLoggedIn(){
return this.isAuthenticated;
}
}
export default new Auth();
import React,{ Component } from 'react';
import { GoogleLogin,Googlelogout} from 'react-google-login';
import auth from './auth';
login (response: any) {
if(response.accesstoken){
this.setState(state => ({
isLogined: true,userName: response.profileObj.givenname + ' ' + response.profileObj.familyName
}));
this.refreshTokenSetup(response);
auth.login();
}
}
render() { //this is what is rendered (what users see) in the react web app pahge
return (
<div>
<GoogleLogin
clientId={ CLIENT_ID }
buttonText='Login'
onSuccess={ this.login}
isSignedIn={true}
onFailure={ this.handleLoginFailure }
cookiePolicy={ 'single_host_origin' }
responseType='code,token'
/>
}
最后,我的受保护路线:
import * as React from 'react';
import {Route,Router,Redirect,RouteProps} from 'react-router-dom';
import auth from './auth';
const ProtectedRoute: React.FC<RouteProps> = ({component: Component,...rest}) => {
if (!Component) return null;
return (
<div>
<Route {...rest} render={props => (
auth.isAuthenticated ?
<Component {...props} />:
<Redirect to="/" />
)} />
</div>
);
};
export default ProtectedRoute;
根据我所遵循的教程,如果他们在ClassX中设置this.isAuthenticated=true
,则在他们导入auth并在ClassA中访问它时该值仍然为true,所以我不知道如何,因为我假设每个实例都创建了新实例他们什么时候导入?
我的问题是:是否可以在一个类中将值编辑为“ true”,然后从另一个类中访问它?
如果没有,关于如何解决问题的任何建议?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)