提交表单时,我运行GraphQL突变。如果成功,我希望在返回令牌并将其存储在本地存储中之后重定向到私有页面/panel
。如果没有,我想显示来自StatusMessage()
函数的错误消息。
问题是,如果登录不成功,则错误消息会正常工作。但如果登录成功,我仍然会重定向到/404
而不是/panel
。但是,当我返回到/login
页面时,这次会自动重定向到/panel
。我不知道第一次出了什么问题。也许令牌会延迟几秒钟返回,而重定向会提前发生?
有解决办法吗?这是我的代码:
function LoginPage (props: any){
const [isSubmitted, setIsSubmitted] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
const [shouldRedirect, setShouldRedirect] = useState(false);
const [removeUser] = useMutation(LoginMutation);
// useEffect(() => {
// if(localStorage.getItem('token')){
// setShouldRedirect(true);
// },[] );
function submitForm(email: string, password: string) {
setIsSubmitted(true);
removeUser({
variables: {
email: email,
password: password,
},
}).then(({ data }: any) => {
localStorage.setItem('token', data.loginEmail.accessToken);
setShouldRedirect(true);
//props.history.push("/panel");
})
.catch((error: { message: string; }) => {
setShouldRedirect(false);
console.log("Error msg:" + error.message);
setErrorMessage(error.message);
})
}
if(shouldRedirect) return <Redirect to="/panel" />;
return (
<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);
};
return (
<form style={{ width: '100%' }}
onSubmit={e => {e.preventDefault();
submitForm(email, password);}}>
<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")}
/>
{isSubmitted && StatusMessage(shouldRedirect, errorMessage)}
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<br />
<Button className='button-center'
type="submit"
disabled={!isValid || !email || !password}
>
Submit</Button>
<br></br>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
</form>
)
}}
</Formik>
</div>
{/* {submitted && <Redirect to='/panel'/>} */}
</Container>
);
}
export default LoginPage;
编辑:这就是我如何做私人路由:
const token = localStorage.getItem('token');
export 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>
<PrivateRoute
path='/panel'
isAuthenticated={token}
component={PanelHomePage}
/>
<Redirect from='*' to='/404' />
</Switch>
</BrowserRouter>
</div>
);
}
您只在脚本加载时读取令牌。因此,一旦用户通过登录表单登录应用程序,他就会被重定向到404,因为您不会从本地存储中重新读取令牌。刷新页面后,您就有了令牌,因此用户就可以登录了。
然而,这并不能解决你们所有的问题,因为你们并没有重新招标应用程序。你必须让isLoggedIn
在应用程序中的某个地方进行检查,以确保你重新发送了组件。