停止重定向 onSubmit() &改为显示错误消息 [英] Stop Redirection onSubmit() & Display Error Message Instead
问题描述
我有一个登录屏幕.如果用户名 &密码正确,令牌存储在本地存储中.如果没有,我会打印一条错误消息登录失败".它工作正常.
但是现在,我在我的代码中添加了重定向.如果用户名 &密码正确,我必须去/面板.如果没有,我必须显示错误消息.但是,目前,如果用户名 &密码不正确,我立即转到/404 页面.我怎样才能解决这个问题?如果输入了错误或未经授权的 URL,我只想转到/404.
登录页面:
function LoginPage(){const [状态,设置状态] = useState({电子邮件: '',密码: '',});const [submitted, setSubmitted] = useState(false);函数显示错误(){if (!localStorage.getItem('token')){console.log('登录失败');返回 (<排版>登录失败</排版>)}}函数表单提交(){设置提交(真);console.log('表单提交');}函数重定向到面板(){console.log('ha');if(submitted && localStorage.getItem('token')){console.log('FInall');return <Redirect to='/panel'/>}}函数 submitForm(LoginMutation: any) {const { 电子邮件,密码 } = 状态;如果(电子邮件和密码){登录变异({变量:{电子邮件:电子邮件,密码:密码,},}).then(({ data }: any) => {localStorage.setItem('token', data.loginEmail.accessToken);}).catch(控制台.log)}}返回 (<突变突变={LoginMutation}>{(LoginMutation: any) =>(<容器组件="main" maxWidth="xs"><CssBaseline/><div 样式={{显示:'弹性',flexDirection: '列',alignItems: '中心'}}><头像><LockOutlinedIcon/></头像><排版组件="h1"变体="h5">登入</排版><福米克initialValues={{ 电子邮件:'',密码:'' }}onSubmit={(values, actions) =>{setTimeout(() => {警报(JSON.stringify(值,空,2));动作.setSubmitting(假);}, 1000);}}验证架构={架构}>{道具=>{常量{值:{电子邮件,密码},错误,感动,处理更改,已验证,setFieldTouched} = 道具;const change = (name: string, e: any) =>{e.persist();handleChange(e);setFieldTouched(name, true, false);setState( prevState => ({ ...prevState, [name]: e.target.value }));};返回 (<form style={{ width: '100%' }}onSubmit={e =>{e.preventDefault();submitForm(LoginMutation);FormSubmitted();RedirectionToPanel()}}><文本字段变体=概述"边距=正常"id="电子邮件"全屏宽度名称=电子邮件"helperText={touched.email ?错误.电子邮件:"}错误={touched.email &&布尔值(errors.email)}标签=电子邮件"值={电子邮件}onChange={change.bind(null, "email")}/><文本字段变体=概述"边距=正常"全屏宽度id="密码"名称=密码"helperText={touched.password ?错误密码:"}错误={touched.password &&布尔值(错误.密码)}标签=密码"类型=密码"值={密码}onChange={change.bind(null, "password")}/>{提交&&显示错误()}<表单控件标签control={<Checkbox value="remember" color="primary"/>}标签=记住我"/><br/><Button className='button-center'类型=提交"禁用={!isValid ||!email ||!密码}//onClick={handleOpen}风格={{背景:'#6c74cc',边界半径:3,边界:0,白颜色',身高:48,填充:'0 30px'}}>提交按钮><br></br><网格容器><网格项目 xs><Link href="#" variant="body2">忘记密码?</链接></网格><网格项目><Link href="#" variant="body2">{"还没有帐户?注册"}</链接></网格></网格></表单>)}}</Formik>
{提交&&<重定向到='/面板'/>}</容器>)}</突变>);}导出默认登录页面;
这是我的 App.tsx 的样子:
const token = localStorage.getItem('token');const PrivateRoute = ({component, isAuthenticated, ...rest}: any) =>{const routeComponent = (props: any) =>(已认证?React.createElement(组件,道具):<重定向到={{路径名:'/404'}}/>);return <Route {...rest} render={routeComponent}/>;};导出默认函数 App() {返回 (<div><浏览器路由器><开关><路由精确路径='/' component= {HomePage}></Route><Route path='/login' component= {LoginPage}></Route><Route path='/404' component= {Error404Page}></Route><私人路线路径='/面板'isAuthenticated={令牌}组件={PanelHomePage}/><重定向 from='*' to='/404'/></开关></BrowserRouter>
);}
在 App.tsx 中对 localStorage.getItem('token')
的更改不会被执行.您可以使用 useState 和 useEffect 解决此问题.
const [token, setToken] = useState('');useEffect(() => {setToken(localStorage.getItem('token'));}, [localStorage.getItem('token')]);...<私人路线路径='/面板'isAuthenticated={令牌}组件={PanelHomePage}/>...
I have a login screen. If the username & password are correct, a token is stored in local storage. If not, I was printing an error message "Login Unsuccessful". It was working properly.
But Now, I have added redirection into my code. If the username & password are correct, I have to go to /panel. If not, I have to display the error message. However, currently, if the username & password are incorrect, I just go to /404 page immediately. How can I fix this? I only want to go to /404 if a wrong or unauthorised url is entered.
Login Page:
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 (
<Typography>
Login Unsuccessful
</Typography>)
}
}
function FormSubmitted(){
setSubmitted(true);
console.log('Form submitted');
}
function RedirectionToPanel(){
console.log('ha');
if(submitted && localStorage.getItem('token')){
console.log('FInall');
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;
This is how my App.tsx looks like:
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}/>;
};
export default function App() {
return (
<div>
<BrowserRouter>
<Switch>
<Route exact path='/' component= {HomePage}></Route>
<Route path='/login' component= {LoginPage}></Route>
<Route path='/404' component= {Error404Page}></Route>
<PrivateRoute
path='/panel'
isAuthenticated={token}
component={PanelHomePage}
/>
<Redirect from='*' to='/404' />
</Switch>
</BrowserRouter>
</div>
);
}
Changes to localStorage.getItem('token')
in App.tsx are not acted upon. You can fix this by using useState and useEffect.
const [token, setToken] = useState('');
useEffect(() => {
setToken(localStorage.getItem('token'));
}, [localStorage.getItem('token')]);
...
<PrivateRoute
path='/panel'
isAuthenticated={token}
component={PanelHomePage}
/>
...
这篇关于停止重定向 onSubmit() &改为显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!