react-router3 - 利用 path-to-regexp 實現路徑及參數的匹配

上節代碼也看到了, 在判斷的時候,是直接拿 props上傳的 path 和 監聽到的 pathname作的全等比較
在這裏插入圖片描述
那這樣的話,如果手動傳入 /about/1, /about/page/2 這樣的路徑就匹配不到了, 肯定會返回 null 的,

path-to-regexp倉庫
在這裏插入圖片描述

path-to-regexp部分用法

// pathToRegexp(str, [], {})傳3個參數, 要匹配的字符串目標,一個數組,最後是一個對象
const { pathToRegexp } = require("path-to-regexp");
// {end: false} 非嚴格匹配,只要有部分一樣就可以通過, 如果是true,就是嚴格匹配
let regxp = pathToRegexp('/home', [], { end: false });
console.log(regxp);
console.log(regxp.test('/home')); // true
console.log(regxp.test('/home/2')); // true
console.log(regxp.test('/home/app/10')); // true

regulex-正則解析圖形化

代碼演示

修改 Route.js 裏的路徑判斷

加入正則匹配庫

import React, { PureComponent } from 'react';
import Context from './Context';
import { pathToRegexp } from 'path-to-regexp';
class Route extends PureComponent {
  static contextType = Context;
  render() {
    // 獲取到用戶傳入的path 和 組件
    const { component: RouteComponent, path, exact = false } = this.props;
    // 獲取到監聽到的變化後的hash值
    const { pathname } = this.context.location;
    // 比較, 如果相等,就渲染對應的組件,否則,渲染null
    let regexp = pathToRegexp(path, [], { end: exact });
    return pathname.match(regexp) ? <RouteComponent /> : null;
  }
}

export default Route;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章