react路由传参

文章类型:React

发布者:hp

发布时间:2023-05-11

在react中,跳转路由经常会遇到携带参数,今天整理一下常用的方式

一:URL参数传递,指将参数通过 URL 地址的形式传递

<Route path="/users/:id" component={User} />

class User extends React.Component {
  render() {
    const { id } = this.props.match.params;
    return <div>User ID: {id}</div>;
  }
}

二:查询参数传递,指将参数通过 URL 地址的查询字符串的形式传递,携带?xxx

import qs from 'qs';

class User extends React.Component {
  render() {
    const { search } = this.props.location;
    const { id } = qs.parse(search, { ignoreQueryPrefix: true });
    return <div>User ID: {id}</div>;
  }
}

三:路由状态传递,指将参数通过路由的 state 属性传递

<Link to={{ pathname: '/users/123', state: { foo: 'bar' } }}>User 123</Link>

class User extends React.Component {
  render() {
    const { foo } = this.props.location.state;
    return <div>User State: {foo}</div>;
  }
}

四:动态路由配置,指根据路由配置动态生成路由,将参数作为组件的 props 传递

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
];

class User extends React.Component {
  render() {
    const { id } = this.props;
    const user = users.find(u => u.id === Number(id));
    return <div>User Name: {user.name}</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <Router>
        <Switch>
          {users.map(user => (
            <Route key={user.id} path={`/users/${user.id}`} render={() => <User id={user.id} />} />
          ))}
        </Switch>
      </Router>
    );
  }
}

五:withRouter,将组件包裹起来,并注入 history, location 和 match 三个 props,就可以在内部访问路由相关信息

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

class MyComponent extends React.Component {
  handleClick = () => {
    const { history } = this.props;
    history.push('/some/path');
  }

  render() {
    return <button onClick={this.handleClick}>Go to /some/path</button>;
  }
}

export default withRouter(MyComponent);

六:URLSearchParams,es6新增,可以对url查询参数进行操作和解析

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

function MyComponent() {
  const searchParams = new URLSearchParams(window.location.search);
  const id = searchParams.get('id');

  return (
    <div>
      <p>id: {id}</p>
      <Link to="/">Go back to homepage</Link>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <Route path="/some/path" component={MyComponent} />
    </BrowserRouter>
  );
}

七:React Router Hooks,useHistory:获取 history 对象,可以在组件中进行编程式导航操作。useParams:获取 URL 参数对象,可以在组件中获取路由参数

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

function MyComponent() {
  const history = useHistory();
  const { id } = useParams();

  return (
    <div>
      <p>id: {id}</p>
      <button onClick={() => history.push('/')}>Go back to homepage</button>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <Route path="/some/path/:id" component={MyComponent} />
    </BrowserRouter>
  );
}

八:context,用于在组件树中传递路由信息。通过 React.createContext() 创建一个 context,然后通过 Router 的 value 属性设置 context 的值,就可以在子组件中访问到路由信息

import { BrowserRouter, Route, Link } from 'react-router-dom';

const RouterContext = React.createContext();

function MyComponent() {
  return (
    <RouterContext.Consumer>
      {({ history }) => (
        <button onClick={() => history.push('/some/path')}>Go to /some/path</button>
      )}
    </RouterContext.Consumer>
  );
}

function App() {
  return (
    <BrowserRouter>
      <RouterContext.Provider value={{ history: BrowserRouter.history }}>
        <Link to="/some/path">Go to /some/path</Link>
        <Route path="/some/path" component={MyComponent} />
      </RouterContext.Provider>
    </BrowserRouter>
  );
}