react实现登录页面跳转
React 登录页面跳转实现方法
使用 React Router 进行导航
安装 react-router-dom 包:
npm install react-router-dom
在应用中配置路由:
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Router>
);
}
登录成功后跳转
在登录组件中使用 useNavigate hook:

import { useNavigate } from 'react-router-dom';
function LoginPage() {
const navigate = useNavigate();
const handleLogin = () => {
// 验证逻辑...
navigate('/dashboard'); // 跳转到仪表盘
};
return (
<button onClick={handleLogin}>登录</button>
);
}
条件跳转(保护路由)
创建受保护的路由组件:
function ProtectedRoute({ children }) {
const isAuthenticated = localStorage.getItem('token');
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
// 使用方式
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
带状态的跳转
传递状态到目标页面:

navigate('/dashboard', { state: { user: currentUser } });
// 在目标组件中获取
const location = useLocation();
const user = location.state?.user;
编程式导航替代方案
使用 useHistory(v5及以下版本):
import { useHistory } from 'react-router-dom';
function LoginPage() {
const history = useHistory();
const handleLogin = () => {
history.push('/dashboard');
};
}
登录后重定向回原页面
存储原始访问路径:
// 在拦截未登录访问时
navigate('/login', { state: { from: location.pathname } });
// 登录成功后
const location = useLocation();
const from = location.state?.from || '/dashboard';
navigate(from, { replace: true });






