How Routing Works
The core principle of routing is to dynamically load the corresponding component based on the URL request.
Installing React Router (Most Common)
npm install react-router-dom --save // 基於 react-router 實作的 lib
npm install @types/react-router-dom --save-deve // 官方沒提供
Usage
React Router's usage is primarily composed of these three parts: BrowserRouter + Switch + Route
app.tsx
<BroserRouter>
<Switch>
<Route exect path="/" component={HomePage} />
<Route path="/sign" render={()=><h1>sign</h1>} />
<Route render={()=><h1>404</h1>} />
</Switch>
</BroserRouter>
exact- Strict, only takes effect on an exact match.Switch- To prevent pages from stacking, useSwitch. Only one page component will be active.- The 404 page should be placed last, so it only takes effect when no other routes match.
How to Pass Parameters via Routes
1. Using "?" to Pass Parameters
http://localhost:3000/product?id=5
2. Using Route Segments to Pass Parameters
http://localhost:3000/product/123456
Getting Route Parameters via RouteComponentProps
import React from "react";
import { RouteComponentProps } from "react-router-dom";
interface MatchParams {
touristRouteId: string;
}
export const DetailPage: React.FC<RouteComponentProps<MatchParams>> = (
props
) => {
// console.log(props.history);
// console.log(props.location);
// console.log(props.match);
return <h1>路游路線詳情頁面, 路線ID: {props.match.params.touristRouteId}</h1>;
};
Getting Route Parameter Info Across Components
When using React Router components, match, history, and location are available by default in the props of child components. However, if you need to pass this information across components:
- Use App Context (you can refer to previous notes)
- HOC (Higher-Order Components)
import React,{Component} from 'react'
import {withRouter} from 'react-router-dom'
class App extends Component{
console.log(this.props); // {match: {…}, location: {…}, history: {…}, 等}
render(){return (<div className='app'></div>)
}
}
export default withRouter(App); // 這里透遛WithRouter將路由參數傳入props中
- Use a Hook function to get them (a simplified way)
import { useHistory, useLocation, useParams, useRouteMatch } from "react-router-dom";
const history = useHistory();
const location = useLocation();
const { touristRouteId }: MatchParams = useParams();
const match = useRouteMatch();
Navigation
There are two main ways to navigate in React:
1. history.push
<Button onClick={() => history.push("signIn")}>登入</Button>
2. Using the Link Component (a wrapper for an <a> tag + history.push)
<Link to={`detail/${id}`}>
連結
</Link>





























Comments