Reactjs登录认证后路由重定向到受保护dashboard页面失效问题排查
问题原因及修复方案
核心问题1:登录成功后未主动触发路由跳转
你的登录页handleSubmit逻辑里只更新了Auth的认证状态,没有执行跳转操作,也没有阻止表单默认提交行为,所以页面不会发生跳转。
修复Login组件:
首先导入路由跳转hook,修改提交逻辑:
// 顶部新增导入 import { useHistory } from 'react-router-dom' const Login = () => { // 新增获取history实例 const history = useHistory() // 原有state定义保持不变... const handleSubmit = (event) => { // 新增:阻止表单默认提交刷新页面的行为 event.preventDefault() const form = event.currentTarget // 可在此处补充你自己的表单校验逻辑,校验通过后执行后续操作 Auth.authenticate() setError(null) setValidated(true) // 新增:登录成功后跳转到仪表盘 history.push('/dashboard') } // 原有return渲染逻辑保持不变... }
核心问题2:PrivateRoute参数传递错误
你自定义的PrivateRoute是接收component参数来渲染受保护组件的,你在App.js里传的是render属性,自定义组件中没有处理这个属性,导致即使认证通过也无法正常渲染Dashboard页面。
修复App.js中PrivateRoute的用法:
<PrivateRoute path="/dashboard" name="Dashboard Page" // 把原来的render属性改成component component={Dashboard} />
可选优化项
1. 避免登录后仍可访问登录页
修改App.js里的登录路由逻辑,已认证用户访问登录页/根路径时直接跳转到仪表盘:
<Route exact path="/login" name="Login Page" render={(props) => Auth.getAuth() ? <Redirect to="/dashboard" /> : <Login {...props} /> } /> <Route exact path="/" name="Home" render={(props) => Auth.getAuth() ? <Redirect to="/dashboard" /> : <Login {...props} /> } />
2. 解决Auth状态非响应式+刷新丢失问题
当前你存在内存里的Auth状态刷新页面就会重置,也无法触发组件自动更新,建议同步到localStorage持久化存储,修改Auth.js:
const Auth = { // 初始化时从localStorage读取认证状态 isAuthenticated: localStorage.getItem('isAuthenticated') === 'true', authenticate() { this.isAuthenticated = true localStorage.setItem('isAuthenticated', 'true') }, signout() { this.isAuthenticated = false localStorage.removeItem('isAuthenticated') }, getAuth() { return this.isAuthenticated }, } export default Auth
内容的提问来源于stack exchange,提问作者anish
相关产品推荐
相关产品推荐

