項目中少不了404頁面的配置,記錄下react-router 配置404頁面的過程
注意:
- 需要用到 Switch 組件包括路由組件(Switch組件保證只渲染其中一個子路由)
- 配置notFount 路由,增加Redirect 組件用於跳轉
import * as React from "react";
import { BrowserRouter as Router, Route, Switch, Redirect, Link } from "react-router-dom";
import Home from "src/pages/home";
import NotFound from "./pages/NotFound"
import List from "./pages/List"
class App extends React.Component {
render() {
return (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/list">list</Link></li>
<li><Link to="/404">404</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/list" component={List} />
// 第一種 地址欄顯示點擊的路由
<Route component={NotFound} />
// 第二種 地址欄顯示/notFound
<Route path="/notFound" component={NotFound} />
<Redirect to="/notFound" />
</Switch>
</div>
</Router>
)
}
}
export default App;