<aside> 📄 本文簡述 React router v6 的功能與使用方法,以及v5升級至v6的過程

</aside>

目錄


定義Route的方法

v5 定義Route的方法

<aside> 👉 RouterSwitchRoute

</aside>

以下範例定義三個Route:

  1. 定義路由“/”顯示 <Home>
  2. 定義路由“/about”顯示 <About>
  3. 都沒有配對到的話,導航到某個地方
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 取代)

v6 定義Routes的方法

<aside> 👉 RouterRoutesRoute

</aside>

以下範例定義四個Routes:

  1. 定義路由“/”顯示 <Home>