react-router 配置404 頁面


項目中少不了404頁面的配置,記錄下react-router 配置404頁面的過程
注意:

  1. 需要用到 Switch 組件包括路由組件(Switch組件保證只渲染其中一個子路由)
  2. 配置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;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM