React Router是React的路由解决方案,它可以讓畫面切換可以與URL同步
Router 經過改動後,新版本與舊版本有些微功能不支援
不支援switch,改用Routes
components 改用 element
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
<Router>
<Routes>
<Route element={<Home />} path={'/'}></Route>
<Route element={List} path='/list'></Route>
</Routes>
</Router>
匯入BrowserRouter、Routes和Link,然後將BrowserRouter重新命名為Router
在react router如果要連到其他頁面我們不使用<a href="/">
,使用<Link to="/">
來替代
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const Index = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const Users = () => <h2>Users</h2>;
const AppRouter = () => (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about/">About</Link>
</li>
<li>
<Link to="/users/">Users</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Index} />
<Route path="/about/" component={About} />
<Route path="/users/" component={Users} />
</div>
</Router>
);
export default AppRouter;