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;

posted @ 2019-06-14 10:40  半夜盗贼  阅读(6100)  评论(1编辑  收藏  举报