React Router v5 版本中,路由传参主要方式

发布于:2024-05-01 ⋅ 阅读:(24) ⋅ 点赞:(0)

在 React Router v5 版本中,路由传参主要有以下几种方式:

1. 动态路由参数(:param

通过在路由路径中使用 : 后跟参数名的形式,可以捕获特定部分的 URL 路径作为参数传递给目标组件。在目标组件中,可以使用 useParams 钩子来获取这些参数。

路由配置

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

// ...

<Route path="/user/:userId" component={UserProfile} />

目标组件

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

function UserProfile() {
  const { userId } = useParams();

  return (
    <div>
      <h1>User Profile: {userId}</h1>
      {/* ... */}
    </div>
  );
}

2. URL 查询参数(?query=value

通过在 URL 后面添加查询参数(query parameters),以 ?key=value 的形式传递。这些参数可以直接附加到 history.push 的 pathname 中,也可以通过 query 对象传递。在目标组件中,可以使用 useLocation 钩子结合 URLSearchParams 来获取查询参数。

跳转代码

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

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

  const handleClick = () => {
    const id = '123'; // 示例值
    history.push(`/user?id=${id}`); // 或 history.push({ pathname: '/user', query: { id } });
  };

  // ...
}

目标组件

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

function UserProfile() {
  const { search } = useLocation();
  const params = new URLSearchParams(search);
  const userId = params.get('id');

  return (
    <div>
      <h1>User Profile: {userId}</h1>
      {/* ... */}
    </div>
  );
}

3. history 对象的 state 属性

通过 history.push 方法的第二个参数(一个对象)传递 statestate 是一个任意的 JavaScript 对象,它不会出现在 URL 中,但会在路由跳转过程中被保存在 history 对象中。在目标组件中,可以通过 useLocation 钩子的 location.state 属性来获取这些数据。

跳转代码

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

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

  const handleClick = () => {
    const user = { id: '123', name: 'John Doe' }; // 示例对象
    history.push('/user', { user });
  };

  // ...
}

目标组件

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

function UserProfile() {
  const { state } = useLocation();
  const { user } = state || {};

  return (
    <div>
      <h1>User Profile: {user.name} ({user.id})</h1>
      {/* ... */}
    </div>
  );
}

综上所述,在 React Router v5 中,您可以使用动态路由参数、URL 查询参数或 history 对象的 state 来实现路由传参。每种方式适用于不同场景,动态路由参数适用于路径中固定位置的参数,查询参数适用于可选参数或需要在 URL 中可见的参数,而 state 适用于不需要在 URL 中显示的私密或复杂数据。


网站公告

今日签到

点亮在社区的每一天
去签到