React Router v6:使用 matchRoutes 进行路由跟踪

问题描述 投票:0回答:4

我们使用自己的内部路线组件来跟踪

react-router-dom
v5 中的路线。看起来大概是这样的:

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

// EDIT: This was React-Router v5 code, in v6 <Switch> is replaced by <Routes>
//       and <Route component={}> is replaced by <Route element={}>

const routes = () => (
  <Switch>
    <TrackedRoute title="title to track" path="/path/home" component={Home} />
    <TrackedRoute title="title to track" path="/path/contact" component={Contact} />
  </Switch>
)

const TrackedRoute = ({ title, ...others }) => {
  doTrackingThings(title);
  return (
    <Route {...others} />
  );
}

但是在 React Router v6 中,Routes 组件只接受它自己的

<Route>
对象。这是通过类型相等来强制执行的。此外,路由路径中不再允许使用可选参数,这使我们的跟踪变得更加复杂。如果我们想跟踪用户所在的路线,我们如何在 React Router v6 中做到这一点?

reactjs react-router react-router-dom
4个回答
2
投票

我们最终将跟踪转移到一个单独的组件。看起来大概是这样的:

import { BrowserRouter, Routes, Route, matchRoutes, useLocation } from 'react-router-dom';

const app = () => (
  <BrowserRouter>
    <Routes>
      <Route path="/path/home" element={<Home />} />
      <Route path="/path/contact" element={<Contact />} />
    </Routes>
    <RouteTracker />
  </BrowserRouter>
);

const RouteTracker = () => {
  // Add our tracking, find all routes that match and track it
  const currentLocation = useLocation();
  const someRoutes = [
    { path: "/path/home" },
    { path: "/path/contact" },
  ];
  const matches = matchRoutes(someRoutes, currentLocation);
  doTrackingThings(matches);
  return null;
}

我们想在一个位置进行跟踪(应用程序很大)。对于其他拥有

<Tracked>
组件(如其他答案所示)的人来说可能更合适。


1
投票

我会制作一个组件,例如跟踪并包裹在 it 元素本身中:

const Tracked = ({title, children})=>{
 doTrackingThings(title);
 return children
}

//then

<Routes>
  <Route path="/home" element={<Tracked title='home'><Home/></Tracked>}/>
</Routes>

0
投票
在 v6 中,

Switch
更改为
Routes
。由于我们有嵌套元素,我们可以将子元素的
props
返回给父元素。

const Tracked = ({title, children})=>{
 // use title here
 return children // as props for the parent 
}

称其为:

<Routes>
  <Route path="/home" element={<Tracked title='title'><Home/></Tracked>}/>
</Routes>

0
投票

您介意我问 RouteTracking 的目的是什么吗?

© www.soinside.com 2019 - 2024. All rights reserved.