Mark Ku's Blog
首頁 關於我
React 學習筆記 - 路由 ( Router ) - Part's 5
Frontend
React 學習筆記 - 路由 ( Router ) - Part's 5
Mark Ku
Mark Ku
July 23, 2022
1 min

路由的原理

路由的原理,依據 url 請求,動態去載入相對應的元件。

安裝 react router ( 最常見 )

npm install react-router-dom --save // 基於 react-router 實作的 lib 
npm install @types/react-router-dom --save-deve // 官方沒提供

使用方法

React 路由用法主要是由這三個所組成
BroserRouter + 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>
  • exect - 嚴謹的,完全匹配,才會生效
  • Switch - 避免頁面推疊,要用使 Switch,只會有一個頁面組件生效。
  • 404 頁面要放在最後一個,所有沒匹配才會生效

如何透過路由傳遞參數

1. 使用 ”?” 來傳遞參數

http://localhost:3000/product?id=5

2. 使用路由 Segments 來 傳遞參數

http://localhost:3000/product/123456

透過 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>;
};

跨元件獲得路由的參數資訊

使用組件 React Route 時,預設會在子組件中 props 取得 match 、history、location ,但如果要跨組件傳遞時則

  • 使用 app context 來做 (可參考先前的筆記)
  • hoc 高階組件
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中

  • 使用 Hook 函數取得 ( 簡化取得 )
import { useHistory, useLocation, useParams, useRouteMatch } from "react-router-dom";
const history = useHistory();
const location = useLocation();
const { touristRouteId }: MatchParams = useParams();
const match = useRouteMatch();

導頁

React 導頁的方式主要有兩種

1. history push

<Button onClick={() => history.push("signIn")}>登入</Button>
<Link to={`detail/${id}`}>
  連結      
</Link>

未完成


Tags

Mark Ku

Mark Ku

Software Developer

8年以上豐富網站開發經驗,直播系統、POS系統、電子商務、平台網站、SEO、金流串接、DevOps、Infra 出身,帶過幾次團隊,目前專注於北美及德國市場電商網站開發團隊。

Expertise

前端(React)
後端(C#)
網路管理
DevOps
溝通
領導

Social Media

facebook github website

Related Posts

NEXTJS 13.3.4 昇級踩坑筆記,Server side component 時代來臨 - migrate page route to app route
NEXTJS 13.3.4 昇級踩坑筆記,Server side component 時代來臨 - migrate page route to app route
May 27, 2023
1 min

Quick Links

關於我

Social Media