从 react-router 迁移到 react-router v6

Posted

技术标签:

【中文标题】从 react-router 迁移到 react-router v6【英文标题】:Migrate from react-router to react router v6 【发布时间】:2022-01-17 04:44:50 【问题描述】:

我正在尝试完成本教程Securing Gatsby With Auth0,但由于到达/路由器与 React 17 不兼容而遇到了障碍。经过一番谷歌搜索后,我发现了这个问题Which router project to use moving forward,它有一个迁移指南:Migrate to React Router from Reach

但是,作为初学者,我还不够精通,无法理解其中包含的内容。

教程源代码如下:

import React from "react"
import  Router  from "@reach/router"
import  Link  from "gatsby"

const Home = () => <p>Home</p>
const Settings = () => <p>Settings</p>
const Billing = () => <p>Billing</p>

const Account = () => (
  <>
    <nav>
      <Link to="/account">Home</Link>" "
      <Link to="/account/settings">Settings</Link>" "
      <Link to="/account/billing">Billing</Link>" "
    </nav>
    <Router>
      <Home path="/account" />
      <Settings path="/account/settings" />
      <Billing path="/account/billing" />
    </Router>
  </>
)

export default Account

从migration guide更新路由器到路由,我把这个改成了:

import React from "react"
import  Link  from "gatsby"
import  Routes  from "react-router-dom";

const Home = () => <p>Home</p>
const Settings = () => <p>Settings</p>
const Billing = () => <p>Billing</p>

const Account = () => (
  <>
    <nav>
      <Link to="/account">Home</Link>" "
      <Link to="/account/settings">Settings</Link>" "
      <Link to="/account/billing">Billing</Link>" "
    </nav>
    <Routes>
      <Home path="/account" />
      <Settings path="/account/settings" />
      <Billing path="/account/billing" />
    </Routes>
  </>
)

export default Account

所以本质上,将Router替换为Routes。现在编译成功,但在运行时失败并出现以下错误:

[Home] 不是&lt;Route&gt; 组件。 &lt;Routes&gt; 的所有子组件 必须是 &lt;Route&gt;&lt;React.Fragment&gt;

因此首页、设置和计费不被视为&lt;Route\&gt;&lt;React.Fragment\&gt;

这是一个简单的例子,适合精通 react-router 的人。我只是在学习这些东西,所以遇到了一些困难。我已要求 auth0 更新本教程,但不知道何时会采取行动,如果有的话。

【问题讨论】:

【参考方案1】:

Routes 组件仅替换 react-router-dom v5 中的 Switch 组件,但需要在 v6 中包装 Route 组件。路由的组件,Home等...需要通过Route来渲染。

import React from "react"
import  Link  from "gatsby"
import  Routes  from "react-router-dom";

const Home = () => <p>Home</p>
const Settings = () => <p>Settings</p>
const Billing = () => <p>Billing</p>

const Account = () => (
  <>
    <nav>
      <Link to="/account">Home</Link>" "
      <Link to="/account/settings">Settings</Link>" "
      <Link to="/account/billing">Billing</Link>" "
    </nav>
    <Routes>
      <Route path="/account" element=<Home /> />
      <Route path="/account/settings" element=<Settings /> />
      <Route path="/account/billing" element=<Billing /> />
    </Routes>
  </>
);

【讨论】:

以上是关于从 react-router 迁移到 react-router v6的主要内容,如果未能解决你的问题,请参考以下文章

从reach/router切换到react-router时,如何设置basename?

如何从 react-router 升级到 react-router-dom?

React-Router:无法从 / 重定向到 /home

如何从 express 重定向到 react-router?

React-Router v6 新特性解读及迁移指南

React-Router6:从入门到实战最佳指南