从反应路由器迁移到反应路由器 v6

Migrate from react-router to react router v6

我正在努力完成本教程Securing Gatsby With Auth0, but have hit a roadblock due to reach/router not being compatible with react 17. After a bit of googling around, I found this issue Which router project to use moving forward which has a migration guide: 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

所以本质上,用Routes代替Router。现在编译成功,但在 运行 时失败并出现此错误:

[Home] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

因此主页、设置和帐单被视为不是 <Route\><React.Fragment\>

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

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>
  </>
);