窥视React Router v6

At the time of this writing, React Router v6 is still in alpha, but the time is about right to start playing with it and exploring what’s to come. This guide will give you a peek at the new features/changes!

在撰写本文时,React Router v6仍处于测试阶段,但现在正是开始使用它并探索将要发生的事情的时候了。 本指南将使您了解新功能/更改!

As you may know, the lead maintainers forked the React Router project to create a lightweight alternative called Reach Router in early 2018.

如您所知,主要维护人员在2018年初分叉了React Router项目,以创建一个名为Reach Router的轻量级替代方案。

During this time, both libraries grew, however it seems that active development for Reach Router will stop, and will be merged into the upcoming React Router v6 🛣

在这段时间里,两个库都在增长,但是似乎Reach Router的活跃开发将停止,并将被合并到即将发布的React Router v6中

With the release coming soon, here’s a sneak peek of what’s coming!

随着即将发布的版本,这是即将发生的事情!

跳到… (Jump to…)

<Switch>变为<Routes> (<Switch> is becoming <Routes>)

This top-level component is going to be renamed. However, its functionality is mostly remaining the same.

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

// v5
import {
  BrowserRouter,
  Switch,
  Route
} from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/"><Home /></Route>
        <Route path="/profile"><Profile /></Route>
      </Switch>
    </BrowserRouter>
  );
}

Just drop <Routes> in there:

只需在其中放置<Routes> :

// v6
import {
  BrowserRouter,
  Routes,
  Route
} from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="profile/*" element={<Profile />} />
      </Routes>
    </BrowserRouter>
  );
}

<Route>的重大更改 (Big Changes with <Route>)

In v6 the <Route> component is receiving the biggest overhaul. Fortunately, these new changes will actually be making it simpler to use!

在v6中, <Route>组件正在接受最大的检修。 幸运的是,这些新更改实际上将使它更易于使用!

The component/render prop will be substituted for the element prop:

component/render道具将代替element道具:

import Profile from './Profile';

// v5
<Route path=":userId" component={Profile} />
<Route
  path=":userId"
  render={routeProps => (
    <Profile routeProps={routeProps} animate={true} />
  )}
/>

// v6
<Route path=":userId" element={<Profile />} />
<Route path=":userId" element={<Profile animate={true} />} />

If you noticed, in v6 it’s much easier to pass props now. This has negated the use of the render prop in v5.

如果您注意到了,在v6中,现在传递道具要容易得多。 这就否定了在v5中使用render prop。

嵌套路线更简单 (Nested Routes are Simpler)

Nested routes in v5 had to be very explicitly defined. This required including a lot of string-matching logic into these components. See <Profile>:

v5中的嵌套路由必须非常明确地定义。 这要求在这些组件中包含许多字符串匹配逻辑。 请参阅<配置文件> :

// v5
import {
  BrowserRouter,
  Switch,
  Route,
  Link,
  useRouteMatch
} from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/profile" component={Profile} />
      </Switch>
    </BrowserRouter>
  );
}

function Profile() {

  let match = useRouteMatch();

  return (
    <div>
      <nav>
        <Link to={`${match.url}/me`}>My Profile</Link>
      </nav>

      <Switch>
        <Route path={`${match.path}/me`}>
          <MyProfile />
        </Route>
        <Route path={`${match.path}/:id`}>
          <OthersProfile />
        </Route>
      </Switch>
    </div>
  );
}

In v6, you can remove the string-matching logic. There isn’t any need for useRouteMatch() either! The result is pleasantly minimal:

在v6中,您可以删除字符串匹配逻辑。 也不需要useRouteMatch() ! 结果令人愉悦地最小:

// v6
import {
  BrowserRouter,
  Routes,
  Route,
  Link,
  Outlet
} from 'react-router-dom';

// Approach #1
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="profile/*" element={<Profile/>} />
      </Routes>
    </BrowserRouter>
  );
}

function Profile() {
  return (
    <div>
      <nav>
        <Link to="me">My Profile</Link>
      </nav>

      <Routes>
        <Route path="me" element={<MyProfile />} />
        <Route path=":id" element={<OthersProfile />} />
      </Routes>
    </div>
  );
}

// Approach #2
// You can also define all
// <Route> in a single place
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="profile" element={<Profile />}>
          <Route path=":id" element={<MyProfile />} />
          <Route path="me" element={<OthersProfile />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function Profile() {
  return (
    <div>
      <nav>
        <Link to="me">My Profile</Link>
      </nav>

      <Outlet />
    </div>
  )
}

Note: the <Outlet> component is used like {this.props.children} in React Router v6. This was a very popular feature from Reach Router!

注意: <Outlet>组件的使用类似于React Router v6中的{this.props.children} 。 这是Reach Router的一项非常受欢迎的功能!

useNavigate代替useHistory (useNavigate Instead of useHistory)

Sometimes you’ll want to programmatically navigate. For example, after a user submits a form and they need to be redirected to a confirmation page. This is the useHistory library in v5, which has been renamed to useNavigate in v6:

有时,您需要以编程方式导航。 例如,在用户提交表单之后,需要将他们重定向到确认页面。 这是v5中的useHistory库,在v6中已重命名为useNavigate

// v5
import { useHistory } from 'react-router-dom';

function MyButton() {
  let history = useHistory();
  function handleClick() {
    history.push('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};

Now history.push() will be replaced with navigate():

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

// v6
import { useNavigate } from 'react-router-dom';

function MyButton() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};

In some cases, you’ll want to replace an URL in the browser history instead of pushing a new URL. This has slightly changed with v6:

在某些情况下,您需要替换浏览器历史记录中的URL,而不是推送新的URL。 在v6中,此更改略有变化:

// v5
history.push('/home');
history.replace('/home');

// v6
navigate('/home');
navigate('/home', {replace: true});

从20kb到8kb (From 20kb to 8kb)

With all of these changes, you’d expect the bundle size to grow, but it’s actually reduced by half! The minified bundle of v5 was ~20kb, and v6 is only ~8kb.

通过所有这些更改,您可以预期捆绑包的大小会增加,但是实际上减少了一半! v5的最小束约为20kb,而v6仅为8kb。

Bundle sizes are calculated using the BundlePhobia tool.

捆绑包大小是使用BundlePhobia工具计算的。

结论 (Conclusion)

I’m pretty excited about the release of React Router v6. Hopefully this article has given you an idea of what to expect when it releases (which should be soon)! You can read more about React Router v6 in the latest release notes 📝

我对React Router v6的发布感到非常兴奋。 希望本文使您对它发布时的期望有所了解(应该很快)! 您可以在最新发行说明中阅读有关React Router v6的更多信息📝

For a complete list of new features, see the official React Router v6 migration guide 🚏

有关新功能的完整列表,请参见官方的React Router v6迁移指南 🚏

翻译自: https://www.digitalocean.com/community/tutorials/react-react-router-v6

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值