簡體   English   中英

停止重定向 onSubmit() 並改為顯示錯誤消息

[英]Stop Redirection onSubmit() & Display Error Message Instead

我有一個登錄屏幕。 如果用戶名和密碼正確,則令牌存儲在本地存儲中。 如果沒有,我會打印一條錯誤消息“登錄失敗”。 它工作正常。

但是現在,我在代碼中添加了重定向。 如果用戶名和密碼正確,我必須去/面板。 如果沒有,我必須顯示錯誤消息。 但是,目前,如果用戶名和密碼不正確,我會立即轉到 /404 頁面。 我怎樣才能解決這個問題? 如果輸入了錯誤或未經授權的 URL,我只想轉到 /404。

登錄頁面:

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 (
    <Typography>
      Login Unsuccessful
      </Typography>)
  }
}

function FormSubmitted(){
  setSubmitted(true);
  console.log('Form submitted');
}

function RedirectionToPanel(){
  console.log('ha');
  if(submitted && localStorage.getItem('token')){
    console.log('FInall');
    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>
                          <Link href="#" variant="body2">
                            Forgot password?
                          </Link>
                        </Grid>
                        <Grid item>
                          <Link href="#" variant="body2">
                            {"Don't have an account? Sign Up"}
                          </Link>
                        </Grid>                    
                      </Grid>
                    </form>
                  )
                }}
              </Formik>
            </div>
            {submitted && <Redirect to='/panel'/>}
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

這是我的 App.tsx 的樣子:

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

export default function App() {
  return (
    <div>
      <BrowserRouter>
      <Switch>
      <Route exact path='/' component= {HomePage}></Route>
      <Route path='/login' component= {LoginPage}></Route>
      <Route path='/404' component= {Error404Page}></Route>
      <PrivateRoute
      path='/panel'
      isAuthenticated={token}
      component={PanelHomePage}
      />
      <Redirect from='*' to='/404' />
      </Switch>
      </BrowserRouter>
    </div>
  );
}

不會對 App.tsx 中對localStorage.getItem('token')的更改采取行動。 您可以使用 useState 和 useEffect 解決此問題。

const [token, setToken] = useState('');

useEffect(() => {
    setToken(localStorage.getItem('token'));
}, [localStorage.getItem('token')]);
...
      <PrivateRoute
      path='/panel'
      isAuthenticated={token}
      component={PanelHomePage}
      />
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM