ReactJS登录成功后无法显示用户名的问题及代码调整方案
问题根源与修改方案
1. 移除Login组件内重复的登录请求,复用App中的登录逻辑
Login组件里同时发起了两次登录请求,且自身创建的axios实例未配置withCredentials: true,会导致会话无法正确保存,进而引发后续状态异常。
修改后的Login组件:
function Login({ handleLogin }) { const navigate = useNavigate(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleSubmit = async (event) => { event.preventDefault(); try { // 直接调用App层的handleLogin处理登录逻辑 await handleLogin(email, password); navigate('/dashboard'); } catch (error) { setError('Invalid email or password'); } } return ( <form onSubmit={handleSubmit}> <label> Email: <input type="email" value={email} onChange={(event) => setEmail(event.target.value)} /> </label> <label> Password: <input type="password" value={password} onChange={(event) => setPassword(event.target.value)} /> </label> <button type="submit">Log in</button> {error && <p>{error}</p>} <p className='already-have-account'>Don't have an account? <Link to="/register">Sign up</Link></p> </form> ); }
2. 确保Dashboard组件能接收user状态
在App.js的路由配置中,给Dashboard组件传入user props:
// App.js路由部分 <Route path="/dashboard" element={<Dashboard user={user} />} />
3. 验证会话一致性
App中的axios实例已配置withCredentials: true,需确保后端登录接口正确设置会话cookie,且跨域配置(若存在跨域)包含Access-Control-Allow-Credentials: true和对应允许的源,保证会话能在前后端间正常传递。
核心逻辑说明
- 移除重复请求后,登录逻辑统一由App层的
handleLogin处理,既避免状态混乱,又复用了带凭证配置的axios实例,确保会话正确保存。 - 给Dashboard传入user状态后,登录成功时
setUser更新全局状态,Dashboard会自动重新渲染并展示用户名。
内容的提问来源于stack exchange,提问作者willd
相关产品推荐
相关产品推荐

