React登录验证后跳转目标页面瞬间返回登录页问题求助
问题与解决方案
问题描述
开发一个包含3种用户角色的React应用,登录页localhost:3000/login设有邮箱和密码输入框。点击登录按钮后,数据发送至Node.js后端查询MySQL数据库,匹配成功后后端返回userId、name、password和role,这一流程运行正常。但根据用户角色跳转时(如医生角色跳转到localhost:3000/doctor),页面会短暂显示目标页面后立刻跳回localhost:3000/login?。移除Axios请求仅保留navigate('/doctor')时,跳转功能正常。当前使用react-router-dom版本为6.6.1,React版本为18.2.0,尝试过用useEffect监听角色变化跳转但未生效。
相关组件代码如下:
Login组件
import { useState } from "react"; import Axios from 'axios'; import { useNavigate } from 'react-router-dom' import './login.css'; const Login = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); let navigate = useNavigate() const handleLogin = () => { Axios.post("http://localhost:3001/login", { email: email, password: password, }, { headers: { 'Content-Type': 'application/json' } } ) .then((response) => { console.log('response 1', response.data[0]['role']) if (response.data[0]['role'] === 'doctor') { navigate('/doctor'); } }); }; return ( <div> <form> <h3>Electronic Prescription System</h3> <h3>Login</h3> <label>Email Address</label> <input className="inputs" type="text" placeholder="email" onChange={(e) => { setEmail(e.target.value) }} /> <label>Password</label> <input className="inputs" type="password" placeholder="password" onChange={(e) => setPassword(e.target.value)} /> <button onClick={handleLogin}>Log in</button> </form> </div> ) }; export default Login;
Main路由组件
import React from 'react'; import { Routes, Route } from 'react-router-dom'; import Login from "./pages/Login/Login"; import Doctor from "./pages/Doctor/Doctor"; import Patient from "./pages/Patient/Patient"; import Pharmacy from "./pages/Pharmacy/Pharmacy"; const Main = () => { return ( <Routes> <Route path="login" element={<Login />} /> <Route path="doctor" element={<Doctor />} /> <Route path="patient" element={<Patient />} /> <Route path="pharmacy" element={<Pharmacy />} /> </Routes> ); } export default Main;
Doctor组件
import { HeaderPanel } from '../../components/headerPanel/headerPanel' import { PrescribePanel } from '../../components/prescribePanel/prescribePanel' import { PrescriptionsList } from '../../components/prescriptionsList/prescriptionsList' import './styles.css'; export const Doctor = () => { return ( <> <HeaderPanel /> <div className='wrapper'> <PrescribePanel /> <PrescriptionsList /> </div> </> ); } export default Doctor
解决方案
问题根源是表单的默认提交行为:登录按钮位于<form>标签内,默认类型为submit,点击时会触发表单提交,导致页面刷新或跳转回登录页,覆盖了navigate的跳转操作。
有两种解决方法:
方法1:阻止事件默认行为
修改handleLogin函数,接收事件参数并调用preventDefault():
const handleLogin = (e) => { // 阻止表单默认提交行为 e.preventDefault(); Axios.post("http://localhost:3001/login", { email: email, password: password, }, { headers: { 'Content-Type': 'application/json' } } ) .then((response) => { console.log('response 1', response.data[0]['role']) if (response.data[0]['role'] === 'doctor') { navigate('/doctor'); } }); };
按钮的onClick无需额外修改,事件会自动传递:
<button onClick={handleLogin}>Log in</button>
方法2:修改按钮类型为button
将登录按钮的type属性设置为button,避免触发表单提交:
<button type="button" onClick={handleLogin}>Log in</button>
两种方法任选其一即可解决跳转后立刻返回登录页的问题。
内容的提问来源于stack exchange,提问作者Nalindaka Hettiarachchi
相关产品推荐
相关产品推荐

