iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 21
2
Modern Web

React 30天系列 第 21

Day 21-這裡不能來,閃閃去旁邊(Redirect)與No Match (404)

前情提要:在前天的react router介紹裡,有提到<Switch>的功能會幫我們匹配第一個符合的<Route>,如果<Route>沒有設定path的話,則永遠會被匹配。另外,當我們想強制將使用者導向其他頁面時可以使用<Redirect>達到我們的目的。

所以今天就來實作這Redirect和NoMatch吧!當然實作對象一樣是萬年好朋友todos

目標說明

  1. 當url的pathname為todos時,todos之後帶有任何路徑參數時都導回todos
  2. 當<Route>和<Redirect>都沒有匹配時,顯示NoMatch component

延續昨天,跟router有關的設定昨天都放在router.js了,開啟router.js後:

Redirect

  1. 從react-router-dom匯入Redirect component
  2. Redirect內設定from和``to```
    • from: 任何path-to-regexp@^1.7.0可以理解的有效URL路徑,任何匹配到的URL參數都送給to處理,沒有匹配到的則直接忽略。(※from只有當Redirect在Switch內部時可使用,詳細內容請參照<Switch children>
    • to: 要redirect的位置。同上,pathname需為任何path-to-regexp@^1.7.0可以理解的有效URL路徑。
  3. 因為不想todos之後的路徑也被匹配到,所以在path="/todos"的Route加上exact,將"/todos"做唯一匹配

NoMatch

  1. 新增Route,不設定path,並將component設定NoMatch,NoMatch就是我們設定的404頁面,當沒有任何路徑匹配時會渲染的內容。

router.js

import React from "react";
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
// ... 
const RootRouter = () => {
  return (
    // ...
    <Switch>
      <Route exact path="/" component={Home} />
      <Route exact path="/todos" component={Todos} />
      <Route path="/news" component={News} />
      <Redirect from="/todos/:id" to="/todos"/>
      <Route component={NoMatch} />
    </Switch>
    // ...
  );
};
// ...

NoMatch.js

import React from 'react';

const NoMatch = () => {
  return (
    <main className="main main-no-content">
      <h1>ಥ_ಥ Page Not Found</h1>
    </main>
  );
};

export default NoMatch;

Redirect操作畫面如下:
https://i.imgur.com/HvbzZDw.gif
NoMatch操作畫面如下:
https://i.imgur.com/E7ddo0B.gif

github傳送門


今日總結:
今天實作了Redirect和No Match(404),明天再來看看Query Parameters吧~


上一篇
Day 20-使用react-router繼續擴增todos吧( ´▽` )ノ
下一篇
Day 22-使用Query Parameters提供todos的過濾條件吧
系列文
React 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言