主程式
分支
主程式 (6.23.1)dev
版本
6.23.1v4/5.xv3.x
useMatches

useMatches

傳回頁面上的當前路由比對。這在父層配置中建立抽象時最為實用,用於存取其子層路由的資料。

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

function SomeComponent() {
  const matches = useMatches();
  // [match1, match2, ...]
}

match 採用以下格式

{
  // route id
  id,

  // the portion of the URL the route matched
  pathname,

  // the data from the loader
  data,

  // the parsed params from the URL
  params,

  // the <Route handle> with any app specific data
  handle,
};

<Route handle>useMatches 配對會變得非常強大,因為您可以將任何您想要的內容放在路由 handle 中,並可以在任何地方存取 useMatches

useMatches 僅與如 createBrowserRouter 等資料路徑器結合使用,因為它們一開始便知道完整的路由樹,並可提供目前所有比對。另外,useMatches 不會比對任何後代路由樹,因為路由器並不知道後代路由。

典型的案例為將麵包屑列新增到使用子層路由資料的父層配置中。

<Route element={<Root />}>
  <Route
    path="messages"
    element={<Messages />}
    loader={loadMessages}
    handle={{
      // you can put whatever you want on a route handle
      // here we use "crumb" and return some elements,
      // this is what we'll render in the breadcrumbs
      // for this route
      crumb: () => <Link to="/messages">Messages</Link>,
    }}
  >
    <Route
      path="conversation/:id"
      element={<Thread />}
      loader={loadThread}
      handle={{
        // `crumb` is your own abstraction, we decided
        // to make this one a function so we can pass
        // the data from the loader to it so that our
        // breadcrumb is made up of dynamic content
        crumb: (data) => <span>{data.threadName}</span>,
      }}
    />
  </Route>
</Route>

現在,我們可以使用自製的 crumb 抽象來建立一個 Breadcrumbs 組件,配合 useMatcheshandle

function Breadcrumbs() {
  let matches = useMatches();
  let crumbs = matches
    // first get rid of any matches that don't have handle and crumb
    .filter((match) => Boolean(match.handle?.crumb))
    // now map them into an array of elements, passing the loader
    // data to each one
    .map((match) => match.handle.crumb(match.data));

  return (
    <ol>
      {crumbs.map((crumb, index) => (
        <li key={index}>{crumb}</li>
      ))}
    </ol>
  );
}

現在,您可以在想要的任何地方轉譯 <Breadcrumbs/>,最好在根組件中。

文件與範例 CC 4.0