Javascript 函数内部的条件呈现
我看到过多个例子,但没有一个适合我的问题。我想在函数组件中使用条件渲染。例如,如果用户未登录且本地存储中不存在令牌,则在提交登录表单时,我希望显示一条消息,说明登录无效Javascript 函数内部的条件呈现,javascript,reactjs,typescript,forms,rendering,Javascript,Reactjs,Typescript,Forms,Rendering,我看到过多个例子,但没有一个适合我的问题。我想在函数组件中使用条件渲染。例如,如果用户未登录且本地存储中不存在令牌,则在提交登录表单时,我希望显示一条消息,说明登录无效 if (!localStorage.getItem('token')) { return <Typography>Login Invalid</Typography> console.log('Login Not possible'); } if(!localStorage.ge
if (!localStorage.getItem('token'))
{
return <Typography>Login Invalid</Typography>
console.log('Login Not possible');
}
if(!localStorage.getItem('token'))
{
返回登录名无效
log('不可能登录');
}
现在,我尝试将其作为一个单独的函数,并在表单的onSubmit()中调用它。但这并没有结果
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;
函数ShowError(){
如果(!localStorage.getItem('token'))
{
返回登录名无效
}
否则{
log('Login Done');
}
}
返回(
{(LoginMutation:any)=>(
{
设置超时(()=>{
警报(JSON.stringify(值,null,2));
动作。设置提交(错误);
}, 1000);
}}
validationSchema={schema}
>
{props=>{
常数{
值:{email,password},
错误,
感动的,
handleChange,
是有效的,
Setfieldtouch
}=道具;
常量更改=(名称:字符串,e:any)=>{
e、 坚持();
handleChange(e);
setFieldTouched(名称、真、假);
setState(prevState=>({…prevState,[名称]:e.target.value}));
};
返回(
{e.preventDefault();
submitForm(LoginMutation);ShowError()}>
提交
忘记密码了?
{“没有帐户?注册”}
{/*
这是一条成功的信息!
*/}
)
}}
)
}
);
}
导出默认登录页面;
如果我这样做{localStorage.getItem('token')&&Invalid Login}
它甚至会在提交表单之前呈现,但我只希望它在表单未提交时出现。
我如何解决这个问题?为什么不在您最终返回之前简单地插入一个条件呢。我通常这样做是为了显示一些错误 假设您的组件名为LoginPage。然后-
function LoginPage() {
...//do something
...//do something
if (!localStorage.getItem('token'))
{
return <Typography>Login Invalid</Typography>
}
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)}}>
<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>
**IF ELSE STATEMENT HERE**
</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;
函数登录页面(){
…做点什么
…做点什么
如果(!localStorage.getItem('token'))
{
返回登录名无效
}
返回(
{(LoginMutation:any)=>(
{
设置超时(()=>{
警报(JSON.stringify(值,null,2));
动作。设置提交(错误);
}, 1000);
}}
validationSchema={schema}
>
{props=>{
常数{
值:{email,password},
错误,
感动的,
handleChange,
是有效的,
Setfieldtouch
}=道具;
常量更改=(名称:字符串,e:any)=>{
e、 坚持();
handleChange(e);
setFieldTouched(名称、真、假);
setState(prevState=>({…prevState,[名称]:e.target.value}));
};
返回(
{e.preventDefault();
submitForm(LoginMutation)}>
提交
忘记密码了?
{“没有帐户?注册”}
**这里的IF-ELSE语句**
{/*
这是一条成功的信息!
*/}
)
}}
)
}
)
}
导出默认登录页面;
您可以使用三元
语句而不是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;
函数isLoggedIn(){
返回localStorage.getItem('token')!='undefined'
}
...
const isLoggedIn=isLoggedIn()
const[FormSubmited,setSubmit]=useState(false)
const[loggedIn,setLoggedIn]=useState(isLoggedIn)
useffect(()=>{
if(loggedIn){
localStorage.set('token',[token])
}
},[loggedIn])
返回(
{(LoginMutation:any)=>(
...
忘记密码了?
{“没有帐户?注册”}
{!loggedIn&&formSubmitted?登录无效:null}
...
)}
);
导出默认登录页面;
函数renderMe(){
如果(!localStorage.getItem('token'))
function renderMe(){
if (!localStorage.getItem('token'))
{
return <ErrorComponent />
}else{
return <Dashboard />
}
}
return renderMe();