Javascript 本地存储中令牌时的PrivateRouting[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

如果我的登录成功,将返回一个身份验证令牌,该令牌存储在本地存储器中。成功登录后,我想通过一条私人路线登录

我找到了这个Javascript代码片段,但我无法使它适用于Typescript。我还没有任何合法的财产。我怎样才能相应地修改它

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')