Mark Ku's Blog

路由的原理

路由的原理,依據 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>

未完成

作者

Mark Ku

擁有 10+ 年經驗的資深軟體工程師,現為 AI 應用 Builder,專注於大型平台架構與簡化複雜系統設計,從電商系統到訂閱與收費平台,結合 AI Agent、AI 整合與自動化開發,打造高效率且可持續演進的產品技術基礎。閱讀更多

覺得這篇有幫助?

作者做的免費工具、每日 Podcast 與電子報,都在這裡。

Mark Ku · 本文採用 CC BY 4.0 授權,轉載請註明作者並附上原文連結。

留言

訂閱電子報

訂閱後即時收到新文章通知,不錯過任何技術分享。

提交即表示同意接收電子報,隨時可

熱門文章

View all
Mark Ku
··603

Oracle Cloud 永久免費方案 Linux 主機及固定 IP :0 元打造雲端解決方案

Oracle Cloud 永久免費方案 Linux 主機及固定 IP :0 元打造雲端解決方案
Mark Ku
··440

告別 Postman 收費陷阱!開源 Git 原生 API 測試神器 Bruno 實戰指南

告別 Postman 收費陷阱!開源 Git 原生 API 測試神器 Bruno 實戰指南
Mark Ku
··323

一款免費開源類似於 Notion 類知識庫系統 — Outline Wiki 佈署與備份全攻略

一款免費開源類似於 Notion 類知識庫系統 — Outline Wiki 佈署與備份全攻略
Mark Ku
··239

打造高效 API 管理平台:從 0 開始部署 Kong Gateway - Part 1

打造高效 API 管理平台:從 0 開始部署 Kong Gateway - Part 1
Mark Ku
··222

在 Ubuntu 上設置 Samba 來共享資料夾,讓 Windows 11 用戶可以存取

在 Ubuntu 上設置 Samba 來共享資料夾,讓 Windows 11 用戶可以存取
Mark Ku
··199

訓練自己的 AI 語音:硬體門檻、開源模型比較與 LoRA 微調

訓練自己的 AI 語音:硬體門檻、開源模型比較與 LoRA 微調
React 學習筆記 - 路由 ( Router ) - Part's 5 - Mark Ku's Blog