Reactjs 使用Reactn和Typescript进行私有路由身份验证
我被困在实现私有路由的部分 因此,以下是我想要最终实现的目标: 我想登录谷歌,一旦我登录我想去一个私人路线页面,如果我注销,我应该不能这样做 对于代码部分: 跟踪登录状态的类(真/假): 谷歌登录的摘要片段:Reactjs 使用Reactn和Typescript进行私有路由身份验证,reactjs,typescript,google-login,Reactjs,Typescript,Google Login,我被困在实现私有路由的部分 因此,以下是我想要最终实现的目标: 我想登录谷歌,一旦我登录我想去一个私人路线页面,如果我注销,我应该不能这样做 对于代码部分: 跟踪登录状态的类(真/假): 谷歌登录的摘要片段: import React, { Component } from 'react'; import { GoogleLogin, GoogleLogout} from 'react-google-login'; import auth from './auth'; login (res
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 React,{Component}来自'React';
从'react google login'导入{GoogleLogin,GoogleLogout};
从“/auth”导入身份验证;
登录(响应:任意){
if(response.accessToken){
this.setState(state=>({
是的,
用户名:response.profileObj.givenName+“”+response.profileObj.familyName
}));
此。刷新令牌设置(响应);
auth.login();
}
}
render(){//这是react web app pahge中呈现的内容(用户看到的内容)
返回(
}
最后,我的受保护路线:
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;
import*as React from'React';
从“react Router dom”导入{Route,Router,Redirect,RouteProps};
从“/auth”导入身份验证;
const ProtectedRoute:React.FC=({component:component,…rest})=>{
如果(!组件)返回空值;
返回(
(
验证了吗?
:
)} />
);
};
导出默认的ProtectedRoute;
根据我遵循的一个教程,如果他们在ClassX中设置了this.isAuthenticated=true
,那么当他们导入auth并在ClassA中访问它时,该值仍然为true,我不知道如何设置,因为我假设每次导入时都会创建新实例
我的问题是:是否可以在一个类中将值编辑为“true”,然后从另一个类访问它,如果可以,如何进行
如果没有,有什么建议可以解决我的问题吗?我会将auth实现为
useAuth
hook,这样您就可以订阅全局值的更新。查看以及如何在此处使用它。我会研究它。谢谢!我会将auth实现为useAuth
hook,这样您就可以订阅gl的更新obal值。看看它以及它如何在这里使用。我会看看的。谢谢!
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;