简体   繁体   English

UseEffect() 不断给出重定向错误

[英]UseEffect() keeps giving error for Redirection

If login is successful, a token is returned and is stored in the local storage.如果登录成功,则返回一个令牌并存储在本地存储中。 In this case, I should redirect to a private route /panel.在这种情况下,我应该重定向到私有路由/面板。 If login is unsuccessful, I should be able to show the error message from ShowError() .如果登录不成功,我应该能够显示来自ShowError()的错误消息。 The error message functionality was working properly before I added the redirection.在我添加重定向之前,错误消息功能正常工作。

This is my LoginPage.tsx这是我的 LoginPage.tsx

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);
  console.log('Form submitted');
}

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

// useEffect(() => {
//   if(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>
                          <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;

Currently, if the login is unsuccessful, it automatically redirects to page /404.目前,如果登录不成功,它会自动重定向到页面 /404。 However, I want it to direct to /404 only if an invalid/private link is entered.但是,我希望它仅在输入无效/私有链接时才指向 /404。 In case of unsuccessful login, I want to show the error message.如果登录失败,我想显示错误消息。

I also tried to use UseEffect() , which is commented out in the code above but it keeps giving me this error on the arrow:我也尝试使用UseEffect() ,它在上面的代码中被注释掉了,但它一直在箭头上给我这个错误:

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)

here is how my private routing is implemented in the App.tsx这是我的私有路由在 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}/>;
};

If I comment out the {submitted && <Redirect to='/panel'/>} , I get the error message on unsuccessful login but then there's no redirection even when the login is successful.如果我注释掉{submitted && <Redirect to='/panel'/>} ,我会在登录失败时收到错误消息,但即使登录成功也没有重定向。

Edited Code:编辑代码:

function LoginPage (){
  const [state, setState] = useState({
    email: '',
    password: '',
  }); 

 const [submitted, setSubmitted] = useState(false);
 const [shouldRedirect, setShouldRedirect] = 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);
//   console.log('Form submitted');
// }

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

useEffect(() => {
    if(localStorage.getItem('token')){
      setShouldRedirect(true);
    }
  },[] );


  function submitForm(LoginMutation: any) {
    setSubmitted(true);
    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);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>
                    </form>
                  )
                }}
              </Formik>
            </div>
            {/* {submitted && <Redirect to='/panel'/>} */}
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

I believe that returning Redirect component shouldn't be called in useEffect hook or inside any function.我认为不应在useEffect钩子或任何函数内部调用返回的Redirect组件。 You should have something like that:你应该有这样的东西:

function LoginPage (){
  const [state, setState] = useState({
    email: '',
    password: '',
  }); 
  const [shouldRedirect, setShouldRedirect] = useState(false);

  useEffect(() => {
    if(localStorage.getItem("token")) {
      setShouldRedirect(true);
    }
  }, []);


  function submitForm(LoginMutation: any) {
    setSubmitted(true);
    const { email, password } = state;
    if(email && password){
      LoginMutation({
          variables: {
          email: email,
          password: password,
        },
     }).then(({ data }: any) => {
       localStorage.setItem('token', data.loginEmail.accessToken);
       setShouldRedirect(true);
     })
    .catch(console.log)
   }
  }
  if(shouldRedirect) return <Redirect to="/panel" />;
  return (
   ... rest of code
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM