编程语言v6新特性解读及迁移指南

    作者:佚名更新于: 2020-03-30 20:58:03

    大神带你学编程,欢迎选课

    React-Router v6新特性解读及迁移指南。在过去的几十年间,大量的编程语言被发明、被取代、被修改或组合在一起。尽管人们多次试图创造一种通用的程序设计语言,却没有一次尝试是成功的。之所以有那么多种不同的编程语言存在的原因是,编写程序的初衷其实也各不相同;新手与老手之间技术的差距非常大,而且有许多语言对新手来说太难学;还有,不同程序之间的运行成本(runtime cost)各不相同。

    本文介绍了React-Router v6 新特性解读和迁移指南 ,我们一起来了解以下吧。

    编程语言v6新特性解读及迁移指南_编程语言_开发_程序员_课课家

    前言

    18 年初,React Router的主要开发人员创建一个名为Reach Router的轻量级替代方案。

    原来是相互抗衡的,却没想React Router直接拿来合并(真香!)

    目前 v6已是测试最后一版,估计新的特性不出意外就是下面这些了:

    1.  重命名为
    2.  的新特性变更。
    3.  嵌套路由变得更简单。
    4.  用useNavigate代替useHistory。
    5.  新钩子useRoutes代替react-router-config。
    6.  大小减少:从20kb到8kb

    1. 重命名为

    该顶级组件将被重命名。但是,其功能大部分保持不变(嗨,瞎折腾)。

    1. // v5  
    2. <Switch>  
    3.     <Route exact path="/"><Home />Route>  
    4.     <Route path="/profile"><Profile />Route>  
    5. Switch>  
    6. // v6  
    7. <Routes>  
    8.     <Route path="/" element={<Home />/>  
    9.     <Route path="profile/*" element={<Profile />/>  
    10. Routes> 

    2. 的新特性变更

    component/render被element替代

    总而言之,简而言之。就是变得更好用了。

    1. import Profile from './Profile';  
    2. // v5  
    3. <Route path=":userId" component={Profile} />  
    4. <Route  
    5.   path=":userId"  
    6.   render={routeProPS => (  
    7.     <Profile routeProps={routeProps} animate={true} />  
    8.   )}  
    9. />  
    10. // v6  
    11. <Route path=":userId" element={<Profile />/>  
    12. <Route path=":userId" element={<Profile animate={true} />/> 

    3. 嵌套路由变得更简单

    具体变化有以下:

    •   已更改为接受子路由。
    •  比更简单的匹配规则。
    •   路径层次更清晰。

    3.1 简化嵌套路由定义

    v5中的嵌套路由必须非常明确定义,且要求在这些组件中包含许多字符串匹配逻辑(活久见啊,终于意识到这个问题了。)

    且看之前的处理:

    1. // v5  
    2. import {  
    3.   BrowserRouter,  
    4.   Switch,  
    5.   Route,  
    6.   Link,  
    7.   useRouteMatch  
    8. } from 'react-router-dom';  
    9. function app() {  
    10.   return (  
    11.     <BrowserRouter>  
    12.       <Switch>  
    13.         <Route exact path="/" component={Home} />  
    14.         <Route path="/profile" component={Profile} />  
    15.       Switch>  
    16.     BrowserRouter>  
    17.   );  
    18. }  
    19. function Profile() {  
    20.   let { path, url } = useRouteMatch();  
    21.   return (  
    22.     <div>  
    23.       <nav>  
    24.         <Link to={`${url}/me`}>My ProfileLink>  
    25.       nav>  
    26.       <Switch>  
    27.         <Route path={`${path}/me`}>  
    28.           <MyProfile />  
    29.         Route>  
    30.         <Route path={`${path}/:id`}>  
    31.           <OthersProfile />  
    32.         Route>  
    33.       Switch>  
    34.     div>  
    35.   );  

    而在v6中,你可以删除字符串匹配逻辑。不需要任何useRouteMatch()!

    1. // v6  
    2. import {  
    3.   BrowserRouter,  
    4.   Routes,  
    5.   Route,  
    6.   Link,  
    7.   Outlet  
    8. } from 'react-router-dom';  
    9. function App() {  
    10.   return (  
    11.     <BrowserRouter>  
    12.       <Routes>  
    13.         <Route path="/" element={<Home />/>  
    14.         <Route path="profile/*" element={<Profile/>/>  
    15.       Routes>  
    16.     BrowserRouter>  
    17.   );  
    18. }  
    19. function Profile() {  
    20.   return (  
    21.     <div>  
    22.       <nav>  
    23.         <Link to="me">My ProfileLink>  
    24.       nav>  
    25.       <Routes>  
    26.         <Route path="me" element={<MyProfile />/>  
    27.         <Route path=":id" element={<OthersProfile />/>  
    28.       Routes>  
    29.     div>  
    30.   );  

    当然,还有更酸爽的操作,直接在路由里定义,然后用接下来的一个新API:Outlet

    3.2 新API:Outlet

    这玩意儿,像极了{this.props.children},具体用法看以下例子:

    1. function App() {  
    2.   return (  
    3.     <BrowserRouter>  
    4.       <Routes>  
    5.         <Route path="/" element={<Home />/>  
    6.         <Route path="profile" element={<Profile />}>  
    7.           <Route path=":id" element={<MyProfile />/>  
    8.           <Route path="me" element={<OthersProfile />/>  
    9.         Route>  
    10.       Routes>  
    11.     BrowserRouter>  
    12.   );  
    13. }  
    14. function Profile() {  
    15.   return (  
    16.     <div>  
    17.       <nav>  
    18.         <Link to="me">My ProfileLink>  
    19.       nav>  
    20.         {/*  
    21.        将直接根据上面定义的不同路由参数,渲染<MyProfile /><OthersProfile />  
    22.         */}  
    23.       <Outlet />  
    24.     div>  
    25.   )  

    3.3 多个

    以前,我们只能 在React App中使用一个 Routes。但是现在我们可以在React App中使用多个路由,这将帮助我们基于不同的路由管理多个应用程序逻辑。

    1. import React from 'react';  
    2. import { Routes, Route } from 'react-router-dom';  
    3. function Dashboard() {  
    4.   return (  
    5.     <div>  
    6.       <p>Look, more routes!p>  
    7.       <Routes>  
    8.         <Route path="/" element={<DashboardGraphs />/>  
    9.         <Route path="invoices" element={<InvoiceList />/>  
    10.       Routes>  
    11.     div>  
    12.   );  
    13. }  
    14. function App() {  
    15.   return (  
    16.     <Routes>  
    17.       <Route path="/" element={<Home />/>  
    18.       <Route path="dashboard/*" element={<Dashboard />/>  
    19.     Routes>  
    20.   );  

    4. 用useNavigate代替useHistory

    从一目了然改到双目失明。。。

    总感觉React Router团队有点儿戏。。。

    1. // v5  
    2. import { useHistory } from 'react-router-dom';  
    3. function MyButton() {  
    4.   let history = useHistory();  
    5.   function handleClick() {  
    6.     history.push('/home');  
    7.   };  
    8.   return <button onClick={handleClick}>Submitbutton>;  
    9. }; 

    现在,history.push()将替换为navigation():

    1. // v6  
    2. import { useNavigate } from 'react-router-dom';  
    3. function MyButton() {  
    4.   let navigate = useNavigate();  
    5.   function handleClick() {  
    6.     navigate('/home');  
    7.   };  
    8.   return <button onClick={handleClick}>Submitbutton>;  
    9. }; 

    history的用法也将被替换成:

    1. // v5  
    2. history.push('/home');  
    3. history.replace('/home');  
    4. // v6  
    5. navigate('/home');  
    6. navigate('/home', {replace: true}); 

    强行达成共识

    5. 新钩子useRoutes代替react-router-config。

    感觉又是一波强行hooks,但还是相对于之前简洁了一些。。。

    1. function App() {  
    2.   let element = useRoutes([  
    3.     { path: '/', element: <Home /> },  
    4.     { path: 'dashboard', element: <Dashboard /> },  
    5.     { path: 'invoices',  
    6.       element: <Invoices />,  
    7.       children: [  
    8.         { path: ':id', element: <Invoice /> },  
    9.         { path: 'sent', element: <SentInvoices /> }  
    10.       ]  
    11.     },  
    12.     // 重定向  
    13.     { path: 'home', redirectTo: '/' },  
    14.     // 404找不到  
    15.     { path: '*', element: <NotFound /> }  
    16.   ]);  
    17.   return element;  

    6. 大小减少:从20kb到8kb

    React Router v6给我们带来方便的同时,还把包减少了一半以上的体积。。。

    感觉可以去看一波源码了。。。

    7. 迁移及其它重要修复...

    官方的迁移指南在这里:React Router v6 迁移指南

    其实上面所列的新特性,基本就是迁移的全部内容了。

    基础的起手式就是更新包:

    1. $ npm install react-router@6 react-router-dom@6  
    2. # or, for a React Native app  
    3. $ npm install react-router@6 react-router-native@6 

    其中我觉得特别需要注意的一点是:React Router v6 使用简化的路径格,仅支持 2 种占位符:动态:id样式参数和*通配符

    以下都是 v6 中的有效路由路径:

    1. /groups  
    2. /groups/admin  
    3. /users/:id  
    4. /users/:id/messages  
    5. /files/*  
    6. /files/:id/*  
    7. /files-* 

    使用RegExp正则匹配的路径将无效:

    1. /users/:id?  
    2. /tweets/:id(\\d+)  
    3. /files/*/cat.jpg 

    v6中的所有路径匹配都将忽略 URL 上的尾部"/"。实际上,已被删除并且在 v6 中无效。这并不意味着您不需要使用斜杠。

    在v5版本之前的路径,存在路由歧义

    1.  当前路径:"/users",则将跳转
    2.  当前路径:"/users/",则将跳转

    React Router v6修复了这种歧义,取消了尾部"/":

    1.  当前路径:"/users",则将跳转
    2.  当前路径:"/users",则将跳转

    其形式更像命令行cd的用法:

    1. // 当前路径为 /app/dashboard  
    2.  
    3. <Link to="stats">               // <a href="/app/dashboard/stats">  
    4. <Link to="../stats">            // <a href="/app/stats">  
    5. <Link to="../../stats">         // <a href="/stats">  
    6. <Link to="../../../stats">      // <a href="/stats">  
    7. // 命令行当前路径为 /app/dashboard  
    8. cd stats                        // pwd is /app/dashboard/stats  
    9. cd ../stats                     // pwd is /app/stats  
    10. cd ../../stats                  // pwd is /stats  
    11. cd ../../../stats               // pwd is /stats  

    编程语言往往使程序员能够比使用机器语言更准确地表达他们所想表达的目的。对那些从事计算机科学的人来说,懂得程序设计语言是十分重要的,因为在当今所有的计算都需要程序设计语言才能完成。

课课家教育

未登录

1