如何阻止已登录用户访问登录/注册页面(React路由场景)
解决已登录用户访问登录/注册页面的问题
你需要创建一个反向权限控制组件,用来阻止已登录用户访问登录、注册这类仅访客可进入的页面,具体步骤如下:
1. 创建GuestOnly组件
新建GuestOnly.jsx文件,逻辑与你现有的Protected组件相反:当检测到用户已登录(存在token)时,自动跳转到首页;未登录则允许访问目标页面。
import React from 'react' import { Outlet, Navigate } from 'react-router-dom' const GuestOnly = () => { const item = JSON.parse(localStorage.getItem('user')) const token = item?.accessToken // 已登录用户直接跳转到首页,replace避免历史记录残留 return token ? <Navigate to="/" replace /> : <Outlet /> } export default GuestOnly
2. 修改路由配置(App.js)
将登录、注册路由包裹在GuestOnly组件的路由下,确保只有未登录用户能访问:
function App() { return( <Router> <Routes> {/* 需要登录才能访问的页面(原保护路由) */} <Route element={<Protected />}> <Route element={<Home />} path="/" exact /> <Route path="/myproducts" element={ <MyProducts /> } /> <Route path="/products/:category" element={ <ProductContent />} /> <Route path="/sell" element={ <Sell />} /> <Route path="/myproducts/" element={ <MyProducts /> } /> <Route path="/singleproduct/:id" element={<SingleProduct />} /> <Route path="/editproduct/:id" element={<EditProduct />} /> </Route> {/* 仅未登录用户可访问的页面 */} <Route element={<GuestOnly />}> <Route path="/register" element={ <Register />} /> <Route path="/login" element={<Login />} /> </Route> </Routes> <ToastContainer /> </Router> ) } export default App
补充说明
- 使用
replace属性:重定向时替换当前历史记录,避免用户点击返回按钮回到登录/注册页面,提升体验。 - 统一状态检查:如果你的项目用Redux管理用户状态,建议从redux store中获取登录状态(替代
localStorage.getItem),保持状态一致性。
内容的提问来源于stack exchange,提问作者Zurcemozz
相关产品推荐
相关产品推荐

