React Router 6:utils篇

124 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第9天,点击查看活动详情

前言

大家好,我是小阵 🔥,一路奔波不停的码字业务员
如果喜欢我的文章,可以关注 ➕ 点赞,与我一同成长吧~😋
加我微信:zzz886885,邀你进群,一起学习交流,摸鱼学习两不误🌟

开开心心学技术大法~~

开心

来了来了,他真的来了~

正文

React18用上了,React Router6你用上了吗?

react-router组成

router有三部分

  • react-router
  • react-router-dom
  • react-router-native

其中react-routerreact-router-domreact-router-native的核心,一般不作为单独包引入。

如果是web端,可直接引用react-router-dom

如果是react-native端,可以使用react-router-native

react-router-dom

组成

  • components
  • hooks
  • routers
  • utils

因为篇幅太长,之前写了React Router6:components篇,和React Router 6:hooks篇,还有React Router 6:Router篇 今天写下utils

utils

react-router暴露出的工具方法

  1. createRoutesFromChildren

    允许通过js生成routes object

    declare function createRoutesFromChildren(
      children: React.ReactNode
    ): RouteObject[];
    ​
    interface RouteObject {
      caseSensitive?: boolean;
      children?: RouteObject[];
      element?: React.ReactNode;
      index?: boolean;
      path?: string;
    }
    
  2. createSearchParams

    生成基于URLSearchParams的简略版本的对象,更多信息参考 URLSearchParams

  3. generatePath

    通常用于生成要跳转的路由path

    generatePath("/users/:id", { id: "42" }); // "/users/42"
    generatePath("/files/:type/*", {
      type: "img",
      "*": "cat.jpg",
    }); // "/files/img/cat.jpg"
    
  4. Location

    React Router中进行路由匹配与路由跳转的重点对象

    注意,这个Location并不由React Router直接暴露,也就是说通过以下方式暴露是不行的

    import { Location } from "react-router-dom"
    

    准确的说,要使用Location,需要结合history一起使用

    import history from 'history'// Push a new entry onto the history stack.
    history.push("/home");
    ​
    // Push a new entry onto the history stack with a query string
    // and some state. Location state does not appear in the URL.
    history.push("/home?the=query", { some: "state" });
    ​
    // If you prefer, use a location-like object to specify the URL.
    // This is equivalent to the example above.
    history.push(
      {
        pathname: "/home",
        search: "?the=query",
      },
      {
        some: state,
      }
    );
    ​
    // Go back to the previous history entry. The following
    // two lines are synonymous.
    history.go(-1);
    history.back();
    

    可以看到我们虽然没有引入Location,但是history操作的却全部都是Location

  5. matchPath

    该方法用于判断当前url是否符合某个路由匹配规则

    • 如果匹配则返回匹配路由的PathMatch对象
    • 如果不匹配则为null
    declare function matchPath<
      ParamKey extends string = string
    >(
      pattern: PathPattern | string,
      pathname: string
    ): PathMatch<ParamKey> | null;
    ​
    interface PathMatch<ParamKey extends string = string> {
      params: Params<ParamKey>;
      pathname: string;
      pattern: PathPattern;
    }
    ​
    interface PathPattern {
      path: string;
      caseSensitive?: boolean;
      end?: boolean;
    }
    

    可以看到跟前面看到的hooks中的useMatch作用非常相似

    事实上,useMatch内部基于matchPath实现

  6. matchRoutes

    匹配符合条件的路由数组

    matchPath作用类似,不同的是

    • matchPath匹配的是Routepath,返回的是PathMatchnull
    • matchRoutes匹配的是整个Route对象,返回的是RouteMatch[]null
    declare function matchRoutes(
      routes: RouteObject[],
      location: Partial<Location> | string,
      basename?: string
    ): RouteMatch[] | null;
    ​
    interface RouteMatch<ParamKey extends string = string> {
      params: Params<ParamKey>;
      pathname: string;
      route: RouteObject;
    }
    
  7. renderMatches

    结合matchRoutes使用,将匹配的routes object渲染成React Element

    declare function renderMatches(
      matches: RouteMatch[] | null
    ): React.ReactElement | null;
    
  8. resolvePath

    见名知意,将topath 字符串转成类似的path object,前面说的hooks中的useResolvedPath基于resolvePath实现

到这里React Router 6的所有功能和使用方法都介绍完毕啦,哈哈哈,开心~

结语

如果文章真的有帮到你,希望可以多多点赞、收藏、关注支持一波呀!!小阵会很开心哒~

文章如有错误或不严谨之处,还望指出,感谢感谢!!!

加油!

往期好文推荐「我不推荐下,大家可能就错过了史上最牛逼vscode插件集合啦!!!(嘎嘎~)😄」