当前位置:首页 > React

react的history如何跳转路由

2026-01-25 13:33:39React

使用 useHistory Hook(React Router v5)

在函数组件中,可以通过 useHistory Hook 获取 history 对象,调用 pushreplacego 等方法实现路由跳转。

react的history如何跳转路由

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  // 跳转到指定路径
  history.push('/target-path');

  // 替换当前路由(不保留历史记录)
  history.replace('/new-path');

  // 返回上一页
  history.goBack();

  // 前进一页
  history.goForward();
}

使用 withRouter 高阶组件(React Router v5)

在类组件中,可以通过 withRouter 高阶组件注入 history 对象。

react的history如何跳转路由

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 Hook(React Router v6)

React Router v6 移除了 useHistory,改用 useNavigate Hook 实现路由跳转。

import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  // 跳转到指定路径
  navigate('/target-path');

  // 替换当前路由(可配置选项)
  navigate('/new-path', { replace: true });

  // 返回上一页
  navigate(-1);

  // 前进一页
  navigate(1);
}

直接操作 history 对象(通用方法)

通过创建自定义 history 对象(如 createBrowserHistory),可以在非组件环境中直接操作路由。

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

// 跳转路由
history.push('/target-path');

// 监听路由变化
history.listen((location) => {
  console.log('路由变化:', location.pathname);
});

注意事项

  • React Router v6 中不再推荐使用 history 直接操作路由,建议优先使用 useNavigate
  • 跳转时可通过对象传递 state 参数:
    navigate('/target', { state: { id: 123 } });
  • 在类组件中使用 React Router v6 时,需通过 useNavigate 的包装器或上下文传递导航方法。

标签: 跳转路由
分享给朋友:

相关文章

react路由如何使用

react路由如何使用

React 路由的基本使用 React 路由通常通过 react-router-dom 库实现,用于管理单页面应用(SPA)中的页面导航。 安装 react-router-dom: npm ins…

jquery页面跳转

jquery页面跳转

jQuery 页面跳转方法 使用 jQuery 实现页面跳转可以通过多种方式完成,以下是几种常见的方法: 使用 window.location.href 通过修改 window.location.h…

js实现跳转页面

js实现跳转页面

使用 window.location.href 实现跳转 通过修改 window.location.href 属性可以跳转到指定 URL。这是最常见且简单的方法,会触发页面刷新并加载新页面。 win…

vue路由实现模式

vue路由实现模式

Vue路由实现模式 Vue Router 提供了两种路由实现模式:Hash 模式和 History 模式。两种模式的主要区别在于 URL 的表现形式以及后端支持的需求。 Hash 模式 Hash 模…

vue实现tab路由

vue实现tab路由

Vue 实现 Tab 路由的方法 在 Vue 中实现 Tab 路由通常需要结合 Vue Router 和动态组件或条件渲染。以下是几种常见方法: 使用 Vue Router 动态路由 配置路由文件…

vue路由实现流程

vue路由实现流程

Vue 路由实现流程 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router 或 yarn add vue-ro…