Javascript 本地存储中令牌时的PrivateRouting[TypeScript]
如果我的登录成功,将返回一个身份验证令牌,该令牌存储在本地存储器中。成功登录后,我想通过一条私人路线登录 我找到了这个Javascript代码片段,但我无法使它适用于Typescript。我还没有任何合法的财产。我怎样才能相应地修改它Javascript 本地存储中令牌时的PrivateRouting[TypeScript],javascript,reactjs,typescript,react-router,apollo,Javascript,Reactjs,Typescript,React Router,Apollo,如果我的登录成功,将返回一个身份验证令牌,该令牌存储在本地存储器中。成功登录后,我想通过一条私人路线登录 我找到了这个Javascript代码片段,但我无法使它适用于Typescript。我还没有任何合法的财产。我怎样才能相应地修改它 const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( fakeAuth.isAuthenti
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? (
<Component {...props}/>
) : (
<Redirect to={{pathname: '/login', state: { from: props.location }
}}/>
)
)}/>
)
const PrivateRoute=({component:component,…rest})=>(
(
伪造的。是否已验证(
) : (
)
)}/>
)
这是我的登录屏幕:
const LoginMutation = gql`
mutation LoginMutation($email: String!, $password: String!) {
loginEmail(email: $email, password: $password)
}
`;
const schema = Yup.object({
email: Yup
.string()
.email('Invalid Email')
.required('Please Enter your Email'),
password: Yup
.string()
.required('Please Enter your password')
});
function LoginPage (){
const [state, setState] = useState({
email: '',
password: '',
loggedIn: false,
});
function submitForm(LoginMutation: any) {
const { email, password } = state;
console.log(email, password)
if(email && password){
LoginMutation({
variables: {
email: email,
password: password,
},
}).then(({ data }: any) => {
localStorage.setItem('token', data.loginEmail);
})
.catch(console.log)
}
}
return (
<Mutation mutation={LoginMutation}>
{(LoginMutation: any) => (
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={schema}
>
{props => {
const {
values: { email, password },
errors,
touched,
handleChange,
isValid,
setFieldTouched
} = props;
const change = (name: string, e: any) => {
e.persist();
handleChange(e);
setFieldTouched(name, true, false);
setState( prevState => ({ ...prevState, [name]: e.target.value }));
};
return (
<form style={{ width: '100%' }} onSubmit={e => {e.preventDefault();submitForm(LoginMutation)}}>
<TextField
variant="outlined"
margin="normal"
id="email"
fullWidth
name="email"
helperText={touched.email ? errors.email : ""}
error={touched.email && Boolean(errors.email)}
label="Email"
value={email}
onChange={change.bind(null, "email")}
/>
<TextField
variant="outlined"
margin="normal"
fullWidth
id="password"
name="password"
helperText={touched.password ? errors.password : ""}
error={touched.password && Boolean(errors.password)}
label="Password"
type="password"
value={password}
onChange={change.bind(null, "password")}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<br />
<Button className='button-center'
type="submit"
disabled={!isValid || !email || !password}
>
Submit</Button>
</form>
)
}}
</Formik>
</div>
)
}
</Mutation>
);
}
export default LoginPage;
const LoginMutation=gql`
变异登录变异($email:String!,$password:String!){
loginEmail(电子邮件:$email,密码:$password)
}
`;
const schema=Yup.object({
电子邮件:是的
.string()
.email(“无效电子邮件”)
.必填('请输入您的电子邮件'),
密码:是的
.string()
.required('请输入您的密码')
});
函数登录页(){
常量[状态,设置状态]=使用状态({
电子邮件:“”,
密码:“”,
洛格丁:错,
});
函数提交形式(LoginMutation:any){
const{email,password}=state;
console.log(电子邮件、密码)
如果(电子邮件和密码){
逻辑置换({
变量:{
电邮:电邮,,
密码:密码,
},
})。然后({data}:any)=>{
localStorage.setItem('token',data.loginEmail);
})
.catch(console.log)
}
}
返回(
{(LoginMutation:any)=>(
登录
{
设置超时(()=>{
警报(JSON.stringify(值,null,2));
动作。设置提交(错误);
}, 1000);
}}
validationSchema={schema}
>
{props=>{
常数{
值:{email,password},
错误,
感动的,
handleChange,
是有效的,
Setfieldtouch
}=道具;
常量更改=(名称:字符串,e:any)=>{
e、 坚持();
handleChange(e);
setFieldTouched(名称、真、假);
setState(prevState=>({…prevState,[名称]:e.target.value}));
};
返回(
{e.preventDefault();submitForm(LoginMutation)}>
提交
)
}}
)
}
);
}
导出默认登录页面;
有一个类似的问题,但它不能回答我的问题,因为我正在本地存储令牌。只需将fakeAuth.isAuthenticated替换为您保存的令牌,您可以将其保存为全局状态,对吗?因此,一般来说,检查用户是否成功登录只是一个布尔属性,取决于用户将重定向到登录页面或受保护页面的情况,这将进入index.tsx文件:
const token = localStorage.getItem('token');
const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => {
const routeComponent = (props: any) => (
isAuthenticated
? React.createElement(component, props)
: <Redirect to={{pathname: '/login'}}/>
);
return <Route {...rest} render={routeComponent}/>;
};
const-token=localStorage.getItem('token');
const PrivateRoute=({component,isAuthenticated,…rest}:any)=>{
常量路由组件=(道具:任意)=>(
认证
?React.createElement(组件、道具)
:
);
返回;
};
并在浏览器路由器/交换机中使用:
<PrivateRoute
path='/panel'
isAuthenticated={token}
component={PrivateContainer}
/>
我如何相应地修改它?这取决于[身份验证的工作方式]。如果令牌的存在意味着用户是loggen,那么最简单的更改是将fakeAuth.isAuthenticated
更改为localStorage.token
是的,我想的是:const userLoggedIn=localStorage.getItem('token')但是,你知道我怎样才能在typescript中实现这一点吗@在大多数情况下,您应该有某种存储(Redux、MobX等)来保存用户的数据。然后你就可以从商店里买到,想用就用。你的意思是什么“我怎么能在typescript中工作呢?哦,是的,我还没有添加Redux。我先补充一下。但另一方面,我基本上是使用grpahql apollo进行身份验证。现在阿波罗本身就是一个国家管理图书馆。在这种情况下,我如何使用apollo?就我个人而言,在这种情况下,我没有apollo缓存的最佳实践。因为对我来说,有时在涉及数据解析和业务逻辑的情况下使用apollo缓存似乎是不合理的。这些东西应该由存储(或后端)处理和保存。身份验证也可能属于此区域。不过,我听说使用阿波罗缓存旁边的商店是不好的做法。但是,我也看到一些指南,人们说你必须使用商店,而不是完全依赖阿波罗缓存。所以这一切都取决于你:)