当前位置:首页 > React

react如何过去路由信息

2026-01-25 11:14:34React

获取当前路由信息

在React中获取当前路由信息通常依赖于路由库。React Router是最常用的路由解决方案,提供多种方式访问路由数据。

使用useLocation钩子

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

function Component() {
  const location = useLocation();
  console.log(location.pathname); // 当前路径
  console.log(location.search);   // 查询参数
  console.log(location.hash);     // hash值
  console.log(location.state);    // 路由状态对象
}

使用useParams获取动态参数

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

function UserPage() {
  const params = useParams();
  console.log(params.id); // 获取如/user/:id中的id值
}

获取路由匹配信息

使用useMatch钩子

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

function Component() {
  const match = useMatch('/users/:id');
  console.log(match?.params.id); // 匹配到的动态参数
}

类组件中获取路由

对于类组件,可以使用高阶组件withRouter(React Router v5及以下):

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

class MyComponent extends React.Component {
  componentDidMount() {
    console.log(this.props.location);
    console.log(this.props.match);
  }
}

export default withRouter(MyComponent);

获取路由历史对象

使用useNavigate钩子(React Router v6)

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

function Component() {
  const navigate = useNavigate();
  // 可以编程式导航并传递状态
  navigate('/new-path', { state: { data: 123 } });
}

获取查询参数

手动解析URLSearchParams

const query = new URLSearchParams(location.search);
const page = query.get('page'); // 获取?page=123中的123

使用第三方库如query-string

import queryString from 'query-string';

const parsed = queryString.parse(location.search);
console.log(parsed.page);

路由上下文访问

在深层子组件中,可以通过React Router的上下文直接访问:

react如何过去路由信息

import { useContext } from 'react';
import { __RouterContext } from 'react-router-dom';

function DeepChild() {
  const { location, match } = useContext(__RouterContext);
  // 使用路由数据
}

注意:React Router v6主要推荐使用钩子API,v5及以下版本兼容类组件方式。实际使用时需根据项目使用的路由版本选择对应方法。

标签: 路由过去
分享给朋友:

相关文章

vue路由跳转实现

vue路由跳转实现

Vue 路由跳转实现方法 在 Vue 中,路由跳转可以通过多种方式实现,以下是常见的几种方法: 声明式导航(模板中使用 <router-link>) 通过 <router-link…

vue这么实现路由过滤

vue这么实现路由过滤

Vue 路由过滤的实现方法 在 Vue 中实现路由过滤通常涉及对路由的访问权限或条件进行控制,以下是几种常见方法: 使用路由守卫(Navigation Guards) 路由守卫可以在路由跳转前进行拦…

vue怎样实现路由跳转

vue怎样实现路由跳转

路由跳转的实现方式 在Vue中,路由跳转主要通过vue-router实现。以下是几种常见的路由跳转方法: 声明式导航 使用<router-link>组件实现跳转,适合模板中使用: &l…

vue3实现路由

vue3实现路由

Vue 3 实现路由的方法 Vue 3 中实现路由通常使用 vue-router 库,以下是具体实现步骤: 安装 vue-router 使用 npm 或 yarn 安装 vue-router: n…

Vue实现动态路由打包

Vue实现动态路由打包

Vue 动态路由打包实现方法 动态路由在 Vue 项目中常用于权限控制或按需加载场景,以下是几种常见的实现方式及打包优化方案: 基于 router.addRoute() 的动态路由 Vue Rout…

vue的路由实现模式

vue的路由实现模式

Vue 路由实现模式 Vue Router 提供了两种路由实现模式:Hash 模式和History 模式。两者在 URL 表现形式、兼容性和服务器配置方面有所不同。 Hash 模式 Hash…