【问题标题】:UseEffect() keeps giving error for RedirectionUseEffect() 不断给出重定向错误
【发布时间】:2020-06-20 19:02:48
【问题描述】:

如果登录成功,则返回一个令牌并存储在本地存储中。在这种情况下,我应该重定向到私有路由 /panel。如果登录不成功,我应该能够显示来自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 &amp;&amp; &lt;Redirect to='/panel'/&gt;},我会收到登录失败的错误消息,但即使登录成功也没有重定向。

编辑代码:

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;

【问题讨论】:

    标签: javascript reactjs typescript react-router react-hooks


    【解决方案1】:

    我相信返回的Redirect 组件不应该在useEffect 钩子或任何函数中调用。 你应该有这样的东西:

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

    【讨论】:

    • 能否请您在 qs 中查看我编辑的代码并指导我在哪里使用 if(shouldRedirect)statement?如果我在返回值之上使用它,则会出现错误。
    • @a125 你在return上面使用的时候出现什么错误?
    • Failed to compile. ./src/pages/login/LoginPage.tsx Line 269:24: Expected an assignment or function call and instead saw an expression @typescript-eslint/no-unused-expressions
    • @a125 这可能是因为您没有像我所做的那样将重定向组件与返回函数写在同一行中。 if(shouldRedirect) return &lt;Redirect to "/panel" /&gt;;
    • 我仍然在/panel上收到Identifier expected.ts(1003) The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)
    猜你喜欢
    • 2023-01-24
    • 2015-05-24
    • 1970-01-01
    • 2019-10-26
    • 2011-12-23
    • 1970-01-01
    • 2020-12-11
    • 2017-10-19
    • 2021-06-25
    相关资源
    最近更新 更多