基本上,react只會有單一的入口,也就是一定從index.js開始執行,不像一般的網頁,可以直接打開任何的html檔案。所以,當我們的程式長大之後,就必須要靠router來幫忙了。首先,安裝react-router-dom,目前最新的版本是6.3.0。(2022/04/14)

<aside> 💡 react router 6與前面的版本有很多差異,參考網路範例時,請注意版本的差異。

</aside>

Untitled

如果無法安裝6.3.0,可以把package.json改成:

{
  "name": "react",
  "version": "1.0.0",
  "description": "React example starter project",
  "keywords": ["react", "starter"],
  "main": "src/index.js",
  "dependencies": {
    "@emotion/react": "11.9.0",
    "@emotion/styled": "11.8.1",
    "@mui/material": "5.6.0",
    "firebase": "9.6.10",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    **"react-router-dom": "6.3.0"**,
    "react-scripts": "4.0.0"
  },
  "devDependencies": {
    "@babel/runtime": "7.13.8",
    "typescript": "4.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [">0.2%", "not dead", "not ie <= 11", "not op_mini all"]
}

設定Router

Router有兩種,一種是BrowserRouter,另一種是HashRouter。主要的差別在於採用BrowserRouter的話,採用的是標準的URL,有些伺服器(如:apache)就必須更動設定才有辦法使用標準的URL,如果,採用HashRouter,則是利用hash,這樣的寫法沒有伺服器的設定問題。如果想要保留切換Router的彈性,可以利用:

import { BrowserRouter as Router } from "react-router-dom";

也就是BrowserRouter重新命名,未來如果需要改成HashRouter,就只需要改一行

import {**HashRouter** as Router} from 'react-router-dom';

接下來,我們設定一個Router,Router裡設定Routes,在Routes裡有很多Route。每個Route包含path跟element,path就是url的路徑名稱,而element就是對應的元件。


    <Router>
      <Routes>
        <Route path="/" element={<Exam />} />
        <Route path="/exam" element={<Exam />} />
        <Route path="/chemistry" element={<Chemistry />} />
      </Routes>
    </Router>

App.js:

import "./styles.css";
import { BrowserRouter as Router } from "react-router-dom";
import { **Routes**, Route } from "react-router-dom";
import Exam from "./Exam";
import Chemistry from "./Chemistry";

//import Exam from "./Exam";

export default function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" **element={<Exam />}** />
        <Route path="/exam" element={<Exam />} />
        <Route path="/chemistry" element={<Chemistry />} />
      </Routes>
    </Router>
  );
}

這時候,會看到Exam的畫面:

Untitled

當網址加上exam時,就開啟Exam了。

Untitled

當網址加上chemistry時,就開啟Chemistry了。

Untitled