在從 React Router V5 遷移到 React Router V6 時,我遇到了新語法的問題。
我是 V6 的新手,但在 V5 中,我在組件名稱中使用了以下代碼:MyComponent.js
RR V5
const theRoute = useRouteMatch();
const myRoutes = [
['Tab One', theRoute.url],
['Tab Two', `${theRoute.url}/details`]
];
目前 V5 的用例:
<AppBar
position="static"
color="primary"
>
<Tabs
value={location.pathname}
textColor="inherit"
>
<Tab
label={myRoutes[0][0]}
value={myRoutes[0][1]}
component={Link}
to={myRoutes[0][1]}
/>
<Tab
label={myRoutes[1][0]}
value={myRoutes[1][1]}
component={Link}
to={myRoutes[1][1]}
/>
</Tabs>
</AppBar>
<div>
<Switch>
<Route path={routes[0][1]}>
<Main />
</Route>
<Route path={routes[1][1]}>
<ShowDetails />
</Route>
</Switch>
</div>
在App.js(父級)內,我有一個呼叫上述MyComponent.js組件的路由,該組件具有嵌套路由。
<div>
<Switch>
<Route path="/info/:id">
<MyComponent />
</Route>
</Switch>
</div>
我意識到這useRouteMatch()在 RR V6 中不再可用,但不確定如何達到我在上面的 V5 中使用的相同結果,現在在 V6 中?
我看了看,useLocation()但似乎沒有用。
uj5u.com熱心網友回復:
應用程式
- 為v6 中替換它的組件切換
Switch組件Routes - 移動
MyComponent到Route組件的elementprop 中,作為 a 傳遞ReactNode,也就是 JSX。 - 在路徑末尾包含一個尾隨路由路徑通配符
"*",以便嵌套路由也可以與此路由匹配。
例子:
<div>
<Routes>
<Route path="/info/:id/*" element={<MyComponent />} />
</Routes>
</div>
我的組件
- 將嵌套路由包裝在
Routes組件中,以便路由匹配作業。嵌套Routes組件將構建相對于渲染它們的父路由的路徑。 - 將路由的子組件移動到
Route組件的element道具中。 - 我建議通過將要為每個路由渲染的組件移動到
myRoutes配置中并從陣列轉換為物件并將myRoutes配置映射到 JSX 來使代碼更加干燥。
例子:
const myRoutes = [
{
name: 'Tab One',
path: "main",
element: <Main />,
},
{
name: 'Tab Two',
path: "details",
element: <ShowDetails />,
},
];
...
const { pathname } = useLocation();
// Compute the "last path segment" to use for the `Tabs` component
// `value` prop. The last path segment will match against the paths
// that are used for the `Tab` component's `value` prop.
const lastSegment = pathname.split("/").slice(-1).join();
...
<AppBar position="static" color="primary" >
<Tabs
value={lastSegment}
textColor="inherit"
>
{myRoutes.map(({ name, path }) => (
<Tab
key={path}
label={name}
value={path}
component={Link}
to={path}
/>
))}
</Tabs>
</AppBar>
<div>
<Routes>
{myRoutes.map(({ element, path }) => (
<Route key={path} path={path} element={element} />
))}
</Routes>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478619.html
上一篇:通過onClick(TypeScript)單擊功能組件時設定反應狀態
下一篇:無法在React中使用NPM包
