我是 React 的新手,我正在關注這個專案。但我堅持在 react-router-dom 的 version6 中轉換嵌套路由。
在 V5 中是這樣的:
應用程式.js
return (
<div>
<Header />
<Switch>
<Route exact path='/' component={HomePage} />
<Route path='/shop' component={ShopPage} />
<Route exact path='/checkout' component={CheckoutPage} />
<Route
exact
path='/signin'
render={() =>
this.props.currentUser ? (
<Redirect to='/' />
) : (
<SignInAndSignUpPage />
)
}
/>
</Switch>
</div>
);
商店頁面
const ShopPage = ({ match }) => (
<div className='shop-page'>
<Route exact path={`${match.path}`} component={CollectionsOverview} />
<Route path={`${match.path}/:collectionId`} component={CollectionPage} />
</div>
);
我想在 V6 中轉換它,我試過如下:
我的 App.js
return (
<div >
<Header />
<Routes>
<Route path='/' element={<HomePage />} />
<Route path='/shop' element={<ShopPage />} />
<Route path='/checkout' element={<CheckoutPage />} />
<Route path='/signin' element={<>
{this.props.currentUser ?
<Navigate to="/" />
:
<SignInAndSignUpPage />
}
</>
}
/>
<Route path='/signin' element={this.props.user ? <Navigate to="/" /> : <SignInAndSignUpPage />} />
</Routes>
</div>
);
我的店鋪
const ShopPage = () => {
let { pathname } = useLocation();
console.log(pathname);
return (
<div className='shop-page'>
<Routes>
<Route path={`${pathname}`} element={<CollectionsOverview />} />
<Route path={`${pathname}/:collectionId`} element={<CollectionItems />} />
</Routes>
</div>
)
};
在路徑名控制臺日志中,我得到了/shop但專案沒有顯示。如何在 v6 中實作嵌套路由?
uj5u.com熱心網友回復:
它看起來就像CollectionsOverview是在"/shop". 嵌套路由在 v6 中的運行方式與在 v5 中的運行方式略有不同。您不需要獲取當前路徑/url 來構建嵌套路由/鏈接,您只需使用相對路由即可。
例子:
const ShopPage = () => {
return (
<div className='shop-page'>
<Routes>
<Route path="/" element={<CollectionsOverview />} />
<Route path=":collectionId" element={<CollectionItems />} />
</Routes>
</div>
);
};
或者,您可以轉換ShopPage為布局路線。
例子:
import { Outlet } from 'react-router-dom';
const ShopPage = () => (
<div className='shop-page'>
<Outlet />
</div>
);
應用程式
return (
<div >
<Header />
<Routes>
<Route path='/' element={<HomePage />} />
<Route path='/shop' element={<ShopPage />}>
<Route index element={<CollectionsOverview />} />
<Route path=":collectionId" element={<CollectionItems />} />
</Route>
<Route path='/checkout' element={<CheckoutPage />} />
<Route
path='/signin'
element={this.props.currentUser
? <Navigate to="/" />
: <SignInAndSignUpPage />
}
/>
<Route
path='/signin'
element={this.props.user
? <Navigate to="/" />
: <SignInAndSignUpPage />
}
/>
</Routes>
</div>
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453251.html
標籤:javascript 反应 反应路由器dom
上一篇:將陣列轉換為物件名稱和值
