简介react-router-dom基本使用

牟星火
2023-12-01

1.下载包

yarn add react-router-dom 

2. 常用HOOK

  • useHistory:返回 history 对象,可以使用 useHistory 进行导航;
  • useLocation:返回当前URL的 location 对象,每当URL发生变化时,它都会返回一个新的位置;
  • useParams:动态参数列表的引用对象,用于获取<Route>中的 match.params (动态参数)
  • useRouteMatch:主要用于访问匹配数据,而无需实际渲染<Route>

3.基本使用

1.useHistory

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

function JumpPage() {
  let history = useHistory();

  function handleClick() {
    history.push("/跳转位置");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go back
    </button>
  );
}

2.useLocation

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  useLocation
} from "react-router-dom";

function usePageViews() {
  let location = useLocation();
  React.useEffect(() => {
    ga.send(["pageview", location.pathname]);
  }, [location]);
}

function App() {
  usePageViews();
  return <Switch>...</Switch>;
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  node
);

3.useParams

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return <div>Now showing post {slug}</div>;
}

ReactDOM.render(
  <Router>
    <Switch>
      <Route exact path="/">
        <HomePage />
      </Route>
      <Route path="/blog/:slug">
        <BlogPost />
      </Route>
    </Switch>
  </Router>,
  node
);

4.useRouteMatch

useRouteMatch 尝试以与<Route>相同的方式匹配当前URL。

import { useRouteMatch } from "react-router-dom";

function BlogPost() {
  let match = useRouteMatch("url");

  // 匹配你想要匹配的url
  return <div />;
}
// ------等比于------
import { Route } from "react-router-dom";

function BlogPost() {
  return (
    <Route
      path="url"
      render={({ match }) => {
        // 匹配你想要匹配的url
        return <div />;
      }}
    />
  );
}

useRouteMatch 钩子也可以:

  • 不接受任何参数并返回当前<Route>
  • 接受单个参数,与matchPath的props参数相同。它可以是一个字符串形式的路径名(类似此例子),也可以是一个带有匹配道具的对象,例如:
const match = useRouteMatch({
  path: "url",
  strict: true,
  sensitive: true
});

 类似资料: