本地存储中的令牌时的私有路由 [TypeScript] [英] PrivateRouting when Token in Local Storage [TypeScript]

查看:26
本文介绍了本地存储中的令牌时的私有路由 [TypeScript]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我登录成功,则返回一个身份验证令牌,该令牌存储在本地存储中.登录成功后,我想走私人路线.

我找到了这段代码 Javascript 片段,但我无法使其适用于 Typescript.我还没有任何 isAuthenticated 属性.我该如何相应地修改它?

const PrivateRoute = ({ component: Component, ...rest }) =>(<Route {...rest} render={props =>(fakeAuth.isAuthenticated ?(<组件{...props}/>) : (<重定向到={{pathname: '/login', state: { from: props.location }}}/>))}/>)

这是我的登录屏幕:

const LoginMutation = gql`突变 LoginMutation($email: String!, $password: String!) {loginEmail(电子邮件:$email,密码:$password)}`;const schema = Yup.object({电子邮件:是的.细绳().email('无效的电子邮件').required('请输入您的电子邮件'),密码:是的.细绳().required('请输入您的密码')});函数登录页面(){const [状态,设置状态] = useState({电子邮件: '',密码: '',登录:假,});函数 submitForm(LoginMutation: any) {const { 电子邮件,密码 } = 状态;控制台日志(电子邮件,密码)如果(电子邮件和密码){登录变异({变量:{电子邮件:电子邮件,密码:密码,},}).then(({ data }: any) => {localStorage.setItem('token', data.loginEmail);}).catch(控制台.log)}}返回 (<突变突变={LoginMutation}>{(LoginMutation: any) =>(<排版组件="h1"变体="h5">登入</排版><福米克initialValues={{ 电子邮件:'',密码:'' }}onSubmit={(values, actions) =>{setTimeout(() => {警报(JSON.stringify(值,空,2));动作.setSubmitting(假);}, 1000);}}验证架构={架构}>{道具=>{常量{值:{电子邮件,密码},错误,感动,处理更改,已验证,setFieldTouched} = 道具;const change = (name: string, e: any) =>{e.persist();handleChange(e);setFieldTouched(name, true, false);setState( prevState => ({ ...prevState, [name]: e.target.value }));};返回 (<form style={{ width: '100%' }} onSubmit={e =>{e.preventDefault();submitForm(LoginMutation)}}><文本字段变体=概述"边距=正常"id="电子邮件"全屏宽度名称=电子邮件"helperText={touched.email ?错误.电子邮件:"}错误={touched.email &&布尔值(errors.email)}标签=电子邮件"值={电子邮件}onChange={change.bind(null, "email")}/><文本字段变体=概述"边距=正常"全屏宽度id="密码"名称=密码"helperText={touched.password ?错误密码:"}错误={touched.password &&布尔值(错误.密码)}标签=密码"类型=密码"值={密码}onChange={change.bind(null, "password")}/><表单控件标签control={<Checkbox value="remember" color="primary"/>}标签=记住我"/><br/><Button className='button-center'类型=提交"禁用={!isValid ||!email ||!密码}>提交</表单>)}}</Formik>

)}</突变>);}导出默认登录页面;

有一个类似的问题,但它没有回答我的情况,因为我将令牌存储在本地存储中.

解决方案

这将进入您的 index.tsx 文件:

const token = localStorage.getItem('token');const PrivateRoute = ({component, isAuthenticated, ...rest}: any) =>{const routeComponent = (props: any) =>(已认证?React.createElement(组件,道具): <重定向到={{pathname: '/login'}}/>);return <Route {...rest} render={routeComponent}/>;};

并在浏览器路由器/交换机中使用它:

If my login in successful, an authentication token is returned, which is stored in the local storage. Upon successful login, I want to go the a private route.

I found this code Javascript snippet but I am unable to make it work for Typescript. I don't have any isAuthenthicated property yet. How could I modify this accordingly?

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{pathname: '/login', state: { from: props.location }
   }}/>
  )
 )}/>
)

Here is my login screen:

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;

There is a similar question but it doesn't answer my case since I'm storing the token in local storage.

解决方案

This will go in your index.tsx file:

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}/>;
};

And use this in the browser router/switch:

<PrivateRoute
    path='/panel'
    isAuthenticated={token}
    component={PrivateContainer}
/>

这篇关于本地存储中的令牌时的私有路由 [TypeScript]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆