<aside> 📄 本文簡述 React router v6 的功能與使用方法,以及v5升級至v6的過程
</aside>
<aside>
👉 Router
→ Switch
→ Route
</aside>
以下範例定義三個Route:
/
”顯示 <Home>
/about
”顯示 <About>
function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Redirect to="xxx" />
</Switch>
<BrowserRouter>
);
}
除此之外,V5 還有很多的定義方法:
// 1. 用component:傳一個componet(Profile)
<Route path="profile" component={Profile} />
// 2. 用render:傳一個有props的componet
<Route
path=":userId"
render={routeProps => (
<Profile routeProps={routeProps} />
)}
/>
// 3. 用children:條件傳componet
<Route
path=":userId"
children={({ match }) => (
match ? (
<Profile match={match} animate={true} />
) : (
<NotFound />
)
)}
/>
// 4. 使用 react-router-config (此方法在v6中已被 Route Object 取代)
<aside>
👉 Router
→ Routes
→ Route
</aside>
以下範例定義四個Routes:
/
”顯示 <Home>