我希望当有人发送错误的用户名或密码时弹出Material-UI小吃栏警报,主要问题是我对React和Material-UI的使用经验为0。这是一个预先配置的练习,用于处理因401错误而卡住的登录页面。我通过对AuthService.js的简单尝试和操作来“解决了它”,如下所示:
const login = async (usernameOrEmail, password) => {
let response;
try {
response = await api.post('/auth/signin', {usernameOrEmail, password});
} catch (error) {
response = error;
alert("Bad credentials, please try again");
}
return response;
}
现在我想要的是使用Material-ui小吃栏而不是警报,这是Auth.page.js的样子:
...all the imports
const AuthPage = ({history}) => {
const { auth, dispatch } = useContext(AuthContext);
const classes = styles();
if (auth.isAuthenticated) {
history.push("/");
}
const submitLoginForm = async ({email, password}, actions) => {
const loginResponse = await authService.login(email, password);
if (!_.isEmpty(loginResponse.data)) {
const {accessToken, tokenType} = loginResponse.data;
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('tokenType', tokenType);
const userResponse = await authService.getCurrentUser();
if (!_.isEmpty(userResponse.data)) {
const user = userResponse.data;
localStorage.setItem('user', JSON.stringify(user));
dispatch({type: 'login'});
}
}
history.push('/');
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Formik
onSubmit={submitLoginForm}
validationSchema={validationSchema}
render={(
values,
errors,
setSubmitting,
setValues,
isSubmitting,
) => (
<Form className={classes.form}>
<Field
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
component={TextField}
/>
<Field
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
component={TextField}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</Form>
)}
>
</Formik>
</div>
</Container>
);
};
AuthPage.propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
export default withRouter(AuthPage);
因此,最后一个主要问题是,当我在try和catch上发现错误时,或者是否需要其他方法来实现它,在哪里以及如何设置material-ui小吃栏弹出。
答案 0 :(得分:0)
https://codesandbox.io/s/gracious-sky-fem1x?fontsize=14
当您要显示小吃栏警报时,只需将其置于行下方
setStatusBase({ msg: "Success", key: Math.random() });