WEB程序员笔记

一个前端开发工程师的个人博客

React Router V5 与 V6

React Router 版本 6 发布了,它很重要,因为它是最广泛使用的 React 库之一。

那么什么是 React 路由器?

React Router 是一个功能齐全的客户端和服务器端路由库,用于 React,一个用于构建用户界面的 JavaScript 库。React Router 在 React 运行的任何地方运行;在网络上,在带有 node.js 的服务器上,以及在 React Native 上。

在 V6 中,发生了很多幕后变化,无论是增强的路径模式匹配算法还是添加了新组件。不仅如此,捆绑包的大小也减少了近 58%。

《React Router V5 与 V6》

因此,这里有一些您可以将现有项目从 React Router v5 升级到 v6 的更改。

更换 SwitchRoutes

在 v6 中,Switch不从react-router-dom. 在早期版本中,我们可以Switch用来包装我们的路线,并编写代码以一次加载其中一个路线。现在我们Routes用来做同样的事情而不是Switch.

Route 定义变更

匹配路由时应该渲染的组件不能写成Route组件的子组件,但它需要一个 prop 调用element,我们必须传递一个 JSX 组件来渲染它。

exact道具不需要再

在版本 6 中,React Router 变得更加出色。引擎盖下发生了一些变化,这使我们能够匹配特定的路由匹配,而无需exact道具的。早些时候,没有exact,任何以相关关键字开头的路径都将被加载,因为匹配过程是从路由定义的顶部到底部完成的。但是现在,我们不必担心这个,因为 React Router 有一个更好的算法来加载特定路径的最佳路由,现在定义的顺序并不重要。

所以,总结这三点,我们可以考虑这个代码片段。

在 v5

import { Switch, Route, Link } from "react-router-dom";
.
.
.
<Switch>
    <Route path="/">
        <Home/>
    </Route>
    <Route exact path="/cryptocurrencies">
        <Cryptocurrencies/>
    </Route>
    <Route exact path="/crypto/:coinId">
        <CryptoDetails/>
    </Route>
    <Route exact path="/exchanges">
        <Exchanges />
    </Route>
</Switch>

在 v6 中

import { Routes, Route, Link } from "react-router-dom";
.
.
.
<Routes>
   <Route path="/" element={<Home />} />
   <Route path="/crypto/:coinId" element={<CryptoDetails />} />
   <Route path="/cryptocurrencies" element={<Cryptocurrencies />} />

   <Route path="/exchanges" element={<Exchanges />} />
</Routes>

无需react-router-config单独 安装

react-router-config 允许我们将路由定义为 javascript 对象,而不是 React 元素,并且它的所有功能都必须在核心 react 路由器 v6 中移动。

//V5
import { renderRoutes } from "react-router-config";

const routes = [
  {
    path: "/",
    exact: true,
    component: Home
  },
  {
    path: "/cryptocurrencies",
    exact: true,
    component: Cryptocurrencies
  },
  {
    path: "/exchanges",
    exact: true,
    component: Exchanges
  }
];

export default function App() {
   return (
     <div>
       <Router>{renderRoutes(routes)}</Router>
     </div>
   );
}




//V6
function App() {
  let element = useRoutes([
    // These are the same as the props you provide to <Route>
    { path: "/", element: <Home /> },
    { path: "/cryptocurrencies", element: <Cryptocurrencies />,
      // Nested routes use a children property
      children: [
        { path: ":coinId", element: <CryptoDetails /> },
      ] 
    },
    {
      path: "/exchanges",
      element: <Exchanges />
    },
  ]);

  // The returned element will render the entire element
  // hierarchy with all the appropriate context it needs
  return element;
}

useHistory 就是现在 useNavigate

React Router v6 现在有导航 api,大多数时候这意味着替换useHistoryuseNavigate.


//V5
import { useHistory } from "react-router-dom";

function News() {
  let history = useHistory();
  function handleClick() {
    history.push("/home");
  }
  return (
    <div>
      <button onClick={()=>{
           history.push("/home");
      }}>Home</button>
    </div>
  );
}


//V6
import { useNavigate } from "react-router-dom";

function News() {
  let navigate = useNavigate();

  return (
    <div>
      <button onClick={()=>{
          navigate("/home");
      }}>go home</button>
    </div>
  );
}

的一些更常见的特征useHistorygogoBackgoForward。这些也可以通过导航 api 来实现,我们只需要提及我们想要向前或向后移动的步数(’+’ 表示向前,’-‘ 表示向后)。所以我们可以编码这些我们可以考虑的功能。

//V5
import { useHistory } from "react-router-dom";

function Exchanges() {
  const { go, goBack, goForward } = useHistory();

  return (
    <>
      <button onClick={() => go(-2)}>
        2 steps back
      </button>
      <button onClick={goBack}>1 step back</button>
      <button onClick={goForward}>1 step forward</button>
      <button onClick={() => go(2)}>
        2 steps forward
      </button>
    </>
  );
}


//V6
import { useNavigate } from "react-router-dom";

function Exchanges() {
  const navigate = useNavigate();

  return (
    <>
      <button onClick={() => navigate(-2)}>
        2 steps back
      </button>
      <button onClick={() => navigate(-1)}>1 step back</button>
      <button onClick={() => navigate(1)}>
        1 step forward
      </button>
      <button onClick={() => navigate(2)}>
        2 steps forward
      </button>
    </>
  );
}

activeStyleactiveClassName道具从<NavLink />

在以前的版本中,我们可以为活动的时间设置单独的类或样式对象<NavLink/>。在 V6 中,删除了这两个道具,而在 Nav Links className 和 style props 的情况下,它们的工作方式略有不同。它们采用一个函数,该函数又提供了一些有关链接的信息,以便我们更好地控制样式。

//V5
<NavLink
  to="/news"
  style={{ color: 'black' }}
  activeStyle={{ color: 'blue' }}>
  Exchanges
</NavLink>

<NavLink
  to="/news"
  className="nav-link"
  activeClassName="active">
  Exchanges
</NavLink>

//V6
<NavLink
  to="/news"
  style={({isActive}) => { color: isActive ? 'blue' : 'black' }}>
  Exchanges
</NavLink>

<NavLink
  to="/news"
  className={({ isActive }) => "nav-link" + (isActive ? "active" : "")}>
  Exchanges
</NavLink>

替换RedirectNavigate

Redirect不再从 导出react-router-dom,而是使用 canNavigate来实现相同的功能。

//V5
import { Redirect } from "react-router-dom";

<Route exact path="/latest-news">
    <Redirect to="/news">
</Route>
<Route exact path="/news">
    <News />
</Route>


//V6
import { Navigate } from "react-router-dom";

<Route path="/latest-news" element={<Navigate replace to="/news">} />
<Route path="/news" element={<Home />} />

请注意,replace里面的道具通过elementRoute。这意味着我们正在替换当前的导航堆栈。没有replace它意味着我们只是将组件推送到现有导航堆栈中。

这就是今天的内容。希望这可以帮助您将 React 项目升级到 React Router V6。

谢谢阅读!!😇😇
编码快乐!!快乐大厦!!

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注