函数内部的条件渲染 [英] Conditional Rendering Inside A Function

查看:64
本文介绍了函数内部的条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了多个示例,但没有一个适合我的问题.我想在功能组件中使用条件渲染.例如,如果用户未登录,并且本地存储中不存在令牌,则在提交登录表单时,我要显示一条消息,表明登录无效.

I have seen multiple examples but none of them fit my problem. I want to use conditional rendering inside a functional component. For example, if the user is not logged in and a token is not present in the local storage, when the login form is submitted, I want to display a message that login is invalid.

if (!localStorage.getItem('token'))
  {
    return <Typography>Login Invalid</Typography>
    console.log('Login Not possible');
  }

现在,我试图将其设为一个单独的函数,并在表单的onSubmit()中对其进行调用.但是没有任何输出.

For now, I tried to make it a separate function and called it in onSubmit() of my form. But there's no output for that.

function ShowError(){
  if (!localStorage.getItem('token'))
  {
    return <Typography>Login Invalid</Typography>
  }
  else{
    console.log('Login Done');
  }
}
        return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
          <Container component="main" maxWidth="xs">
            <CssBaseline />
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center'
            }}>
              <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); ShowError()}}>
                      <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")}
                      />
                      <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>
                      {/* <Snackbar open={open} autoHideDuration={6000} >
        <Alert severity="success">
          This is a success message!
        </Alert>
      </Snackbar> */}
                    </form>
                  )
                }}
              </Formik>
            </div>
            <Box mt={8}>
              <Copyright />
            </Box>
          </Container>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

f我这样做{localStorage.getItem('token') && <Typography>Invalid Login</Typography>}

即使在提交表单之前也将呈现它,但我只希望在未提交表单时显示它. 我该如何解决?

it will be rendered even before the form is submitted but I only want it to appear if the form is not submitted. How can I fix this?

推荐答案

您可以使用ternary语句代替if/else

function isLoggedIn(){
  return typeof localStorage.getItem('token') !== 'undefined'
}

...

const isLoggedIn = isLoggedIn()
const [formSubmitted, setSubmit] = useState(false)
const [loggedIn, setLoggedIn] = useState(isLoggedIn)

useEffect(() => {
  if (loggedIn) {
   localStorage.set('token', [token])
  }
}, [loggedIn])

return (
  <Mutation mutation={LoginMutation}>
    {(LoginMutation: any) => (
      ...
      <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>
        {!loggedIn && formSubmitted  ? <Typography>Login Invalid</Typography> : null}
      </Grid>
      ...
    )}
  </Mutation>
);

export default LoginPage;

这篇关于函数内部的条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆