登录跳转前显示Material UI Snackbar的实现方案
解决登录成功后先显示Snackbar再跳转的问题
问题核心:登录成功后直接调用navigate("/home")会立即卸载Login组件,导致Material UI的Snackbar还没来得及渲染展示就被销毁,因此无法看到提示。
方案一:固定延迟跳转
在设置showSuccess为true后,用setTimeout延迟执行页面跳转,确保Snackbar有足够时间显示:
修改login函数:
const login = (e) => { e.preventDefault() Axios.post("http://localhost:3001/login", { email: emailLog, password: passwordLog }).then((response) => { if(response.data.message) { setShowWarning(true) } else { setLoginStatus(response.data[0].email); setShowSuccess(true); // 延迟3秒跳转至首页 setTimeout(() => { navigate("/home"); }, 3000); } }) }
方案二:结合Snackbar自动关闭事件跳转
利用Snackbar的onClose回调,当Snackbar因自动超时关闭时再执行跳转,匹配你设置的autoHideDuration={6000},保证用户完整看到提示:
- 修改
handleNotShowSuccess函数:
const handleNotShowSuccess = (event, reason) => { if (reason === 'clickaway') { return; } setShowSuccess(false); // 仅当Snackbar自动超时关闭时跳转 if (reason === 'timeout') { navigate("/home"); } };
- 移除
login函数中直接跳转的代码:
const login = (e) => { e.preventDefault() Axios.post("http://localhost:3001/login", { email: emailLog, password: passwordLog }).then((response) => { if(response.data.message) { setShowWarning(true) } else { setLoginStatus(response.data[0].email); setShowSuccess(true); // 移除原有的navigate("/home") } }) }
两种方案对比:
- 方案一:简单直接,固定延迟时间,适合需要严格控制跳转时机的场景。
- 方案二:更贴合Material UI组件的行为,确保用户看完提示后再跳转,体验更流畅。
内容的提问来源于stack exchange,提问作者RAHMAN DHIKA
相关产品推荐
相关产品推荐

