gpt4 book ai didi

reactjs - 从 react 路由器迁移到 react 路由器 v6

转载 作者:行者123 更新时间:2023-12-05 05:51:40 24 4
gpt4 key购买 nike

我正在尝试完成本教程 Securing Gatsby With Auth0 , 但由于 reach/router 与 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

所以本质上,用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 组件,但需要包装 Route v6 中的组件。路由组件、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>
</>
);

关于reactjs - 从 react 路由器迁移到 react 路由器 v6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70339271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com