react如何做到页面跳转
页面跳转的实现方法
在React中实现页面跳转通常有两种主流方式:使用React Router进行客户端路由跳转,或通过编程式导航控制页面切换。以下是具体实现方案:
使用React Router进行声明式导航
安装React Router依赖包:
npm install react-router-dom
在根组件中配置路由:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Router>
);
}
使用Link组件实现跳转:
import { Link } from 'react-router-dom';
function NavBar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
);
}
编程式导航实现
在类组件中使用withRouter高阶组件:
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
handleClick = () => {
this.props.history.push('/target-path');
};
render() {
return <button onClick={this.handleClick}>跳转</button>;
}
}
export default withRouter(MyComponent);
在函数组件中使用useNavigate钩子:

import { useNavigate } from 'react-router-dom';
function MyComponent() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/target-path')}>
跳转
</button>
);
}
路由参数传递
通过URL参数传递数据:
navigate('/user/123'); // 跳转时传递
// 路由配置
<Route path="/user/:id" element={<UserPage />} />
// 组件内获取
const { id } = useParams();
通过state传递复杂对象:
navigate('/target', {
state: { userData: { name: 'John' } }
});
// 目标组件获取
const location = useLocation();
const userData = location.state?.userData;
重定向处理
使用Navigate组件实现条件重定向:
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ isAuth }) {
return isAuth ? <Dashboard /> : <Navigate to="/login" />;
}
编程式重定向:

const navigate = useNavigate();
useEffect(() => {
if (!isAuth) {
navigate('/login', { replace: true });
}
}, [isAuth]);
路由守卫实现
创建高阶组件保护路由:
function PrivateRoute({ children }) {
const auth = useAuth();
return auth ? children : <Navigate to="/login" />;
}
// 使用方式
<Route path="/dashboard" element={
<PrivateRoute>
<Dashboard />
</PrivateRoute>
} />
路由动画效果
使用React Transition Group实现过渡动画:
import { CSSTransition } from 'react-transition-group';
<Routes>
<Route path="/" element={
<CSSTransition in timeout={300} classNames="fade">
<HomePage />
</CSSTransition>
}/>
</Routes>
配套CSS样式:
.fade-enter {
opacity: 0;
}
.fade-enter-active {
opacity: 1;
transition: opacity 300ms;
}
.fade-exit {
opacity: 1;
}
.fade-exit-active {
opacity: 0;
transition: opacity 300ms;
}
路由懒加载优化
使用React.lazy实现代码分割:
const AboutPage = React.lazy(() => import('./AboutPage'));
<Route path="/about" element={
<Suspense fallback={<Spinner />}>
<AboutPage />
</Suspense>
} />






