簡體   English   中英

UseEffect() 不斷給出重定向錯誤

[英]UseEffect() keeps giving error for Redirection

如果登錄成功,則返回一個令牌並存儲在本地存儲中。 在這種情況下,我應該重定向到私有路由/面板。 如果登錄不成功,我應該能夠顯示來自ShowError()的錯誤消息。 在我添加重定向之前,錯誤消息功能正常工作。

這是我的 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;

目前,如果登錄不成功,它會自動重定向到頁面 /404。 但是,我希望它僅在輸入無效/私有鏈接時才指向 /404。 如果登錄失敗,我想顯示錯誤消息。

我也嘗試使用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)

這是我的私有路由在 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}/>;
};

如果我注釋掉{submitted && <Redirect to='/panel'/>} ,我會在登錄失敗時收到錯誤消息,但即使登錄成功也沒有重定向。

編輯代碼:

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;

我認為不應在useEffect鈎子或任何函數內部調用返回的Redirect組件。 你應該有這樣的東西:

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