首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在某些情况下仅重定向

在某些情况下仅重定向
EN

Stack Overflow用户
提问于 2020-03-08 13:55:02
回答 1查看 97关注 0票数 0

我已经实现了这样的私有路由。如果localStorage中存在令牌,则可以访问私有路由。如果没有,我们应该重定向到/404页面:

代码语言:javascript
运行
复制
const token = localStorage.getItem('token');
const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => {
  const routeComponent = (props: any) => (
      isAuthenticated
          ? React.createElement(component, props)
          : <Redirect to={{pathname: '/404'}}/>
  );
  return <Route {...rest} render={routeComponent}/>;
};

但是我也在我的LoginPage中使用重定向。

我希望如果登录失败,将显示来自ShowError()的错误消息。而不是重定向。在我添加重定向之前,这是正常工作的。如果登录成功,我应该转到/panel。但是,现在,如果登录失败,我只需转到/404。而不是显示错误消息。我怎么才能解决这个问题?

登录屏幕:

代码语言:javascript
运行
复制
function LoginPage (){
  const [state, setState] = useState({
    email: '',
    password: '',
  }); 

 const [submitted, setSubmitted] = useState(false);
function ShowError(){
  if (!localStorage.getItem('token'))
  {
    console.log('Login Not Successful');
    return (
      <ThemeProvider theme={colortheme}>
    <Typography color='primary'>
      Login Unsuccessful
      </Typography>
      </ThemeProvider>)
  }
}

function FormSubmitted(){
  setSubmitted(true);
}

function RedirectionToPanel(){
  if(submitted && localStorage.getItem('token')){
    return <Redirect to='/panel'/>
  }
}

  function submitForm(LoginMutation: any) {
    const { email, password } = state;
    if(email && password){
      LoginMutation({
        variables: {
            email: email,
            password: password,
        },
    }).then(({ data }: any) => {
      localStorage.setItem('token', data.loginEmail.accessToken);
    })
    .catch(console.log)
    }
  }

    return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
          <Container component="main" maxWidth="xs">
            <CssBaseline />
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center'
            }}>
              <Avatar>
                <LockOutlinedIcon />
              </Avatar>
              <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);FormSubmitted();RedirectionToPanel()}}>
                      <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")}
                      /> 
                      {submitted && ShowError()}

                      <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                      />
                      <br />
                      <Button className='button-center'
                        type="submit"
                        disabled={!isValid || !email || !password}
                        // onClick={handleOpen}
                        style={{
                          background: '#6c74cc',
                          borderRadius: 3,
                          border: 0,
                          color: 'white',
                          height: 48,
                          padding: '0 30px'
                        }}
                      >                       
                        Submit</Button>
                      <br></br>
                      <Grid container>
                        <Grid item xs>
                    </form>
                  )
                }}
              </Formik>
            </div>
            {submitted && <Redirect to='/panel'/>}
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

编辑::

我也试过用这个:

代码语言:javascript
运行
复制
  if(localStorage.getItem('token')){
    return <Redirect to='/panel'/>
  }
});

但是它给了我一个箭头上的错误:

代码语言:javascript
运行
复制
Argument of type '() => JSX.Element | undefined' is not assignable to parameter of type 'EffectCallback'.
  Type 'Element | undefined' is not assignable to type 'void | (() => void | undefined)'.
    Type 'Element' is not assignable to type 'void | (() => void | undefined)'.
      Type 'Element' is not assignable to type '() => void | undefined'.
        Type 'Element' provides no match for the signature '(): void | undefined'.ts(2345)
EN

回答 1

Stack Overflow用户

发布于 2020-03-08 14:18:04

在容器的末尾移除这一行。

代码语言:javascript
运行
复制
{submitted && <Redirect to='/panel'/>}

因为去那里是没有意义的。此外,调整submit方法以正确执行函数。

代码语言:javascript
运行
复制
function submitForm(LoginMutation: any) {
   const { email, password } = state;
   return LoginMutation({
     variables: {
       email,
       password,
     },
   }).then(({ data }: any) => {
      localStorage.setItem('token', data.loginEmail.accessToken);
   }).catch(console.error);
}

有了从submitForm方法返回的承诺,您可以执行以下操作。

代码语言:javascript
运行
复制
onSubmit={e => {
   e.preventDefault();
   submitForm(LoginMutation).then((res: any) => {
      RedirectionToPanel();
      FormSubmitted();
   });
}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60588203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档