【问题标题】:Migrate from react-router to react router v6从 react-router 迁移到 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 更新本教程,但不知道何时会采取行动,如果有的话。

【问题讨论】:

    标签: reactjs react-router gatsby react-router-dom 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>
      </>
    );
    

    【讨论】:

      猜你喜欢
      • 2022-10-11
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 2022-01-21
      • 2017-09-13
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多