[React Router v4] Render Catch-All Routes with the Switch Component

本文介绍如何在 React Router v4 中设置一个通用的 404 路由,当用户访问不存在的页面时显示 'Page not found'。通过使用 Switch 和 Route 组件,可以轻松实现自定义的错误页面展示。

There are many cases where we will need a catch-all route in our web applications. This can include 404-style routes when nothing is match or other use cases where where we receive an invalid route in React Router v4.

 

We can use 'Switch' from 'react-router-dom', what 'Switch' will do is only render the first route that matches.

To make a fallback Route, all we need to do is define a Route without any path.

<Route render={() => <h1>Page not found</h1>} />

 

import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch,
} from 'react-router-dom';


const Links = () =>
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/contact/xxx/xxx/xxxx/x">Contact</Link>
    </nav>

const App = (props) => (
  <Router basename={props.path}>
    <div>
      <Links />
      <Switch>
        <Route exact path="/" render={() => <h1>Home</h1>} />
        <Route path="/about" render={() => <h1>About</h1>} />
        <Route render={() => <h1>Page not found</h1>} />
      </Switch>
    </div>
  </Router>
)

export default App

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值