我们使用我们自己的内部路由组件来跟踪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路由器v6中,路由组件只接受自己的<Route>对象。这是通过类型相等强制执行的。此外,在路由路径中不再允许可选的params,这使得我们的跟踪变得更加复杂。如果我们想要跟踪用户在哪一条路由上,我们如何在React路由器v6中做到这一点?
发布于 2022-08-29 14:13:01
最后,我们将跟踪移动到一个单独的组件。看起来大概是这样的:
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>组件可能是更合适的。
发布于 2022-08-29 15:07:25
我会制作一个组件,例如跟踪和包装元素本身:
const Tracked = ({title, children})=>{
doTrackingThings(title);
return children
}
//then
<Routes>
<Route path="/home" element={<Tracked title='home'><Home/></Tracked>}/>
</Routes>发布于 2022-08-30 03:30:55
Switch在v6中更改为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>https://stackoverflow.com/questions/73530162
复制相似问题