javascript - 无法使用 react-router-dom 5.2.0 编写嵌套路由?
问题描述
我正在尝试使用 react-router-dom 5.2.0 在 React 中访问具有嵌套路由的子组件。在这里您可以找到项目的 CodeSandbox 链接:https ://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js
首先,让我向您展示我的页面的树结构。
- 家
- 关于
- 组织
- 主要内容
- 第二内容
主页(主页、关于、组织)的路由位于 src/routes 文件夹中。所以他们的链接看起来像:
- https://localhost:3000/(用于家庭)
- https://localhost:3000/about(关于)
- https://localhost:3000/organizations(对于组织)
在这一点上,一切对我来说都很好。问题出在嵌套部分..
在组织页面上,我必须能够在 MainContent 和 SecondContent 之间切换。因此,该页面的链接必须如下所示:
但我无法打印任何这些内容......
解决方案
如果你想构建嵌套路径,你应该使用当前路由匹配中的 andpath
并url
从那里构建嵌套路由和链接。
src/pages/组织
import { Switch, Route, useRouteMatch } from "react-router-dom";
const Organizations = (props) => {
const { path, url } = useRouteMatch(); // <-- get current path and url
const [value, setValue] = useState("");
const menuLinks = {
data: [
{
id: 0, // <-- fix React key issue in NavBar
title: "StackOverflow",
to: `${url}/maincontent` // <-- build nested link
},
{
id: 1, // <-- fix React key issue in NavBar
title: "BitBucket",
to: `${url}/secondcontent` // <-- build nested link
}
]
};
return (
<div>
<NavBar changeValue={(value) => setValue(value)} menuLinks={menuLinks} />
<div>
<Switch>
<Route
render={() => <MainContent title={value} />} // *
exact
path={`${path}/maincontent`} // <-- build nested path
strict
/>
<Route
render={() => <SecondContent title={value} />} // *
exact
path={`${path}/secondcontent`} // <-- build nested path
strict
/>
</Switch>
</div>
</div>
);
};
*render
请注意,我通过道具而不是道具转换为渲染路线组件component
。当您使用匿名函数渲染组件时,它会在每个渲染周期创建,即每次都会重新安装组件。render
道具不这样做。有关更多信息,请参阅渲染方法。
导航栏
修复to
prop 值以正确渲染链接,从路径中删除前导“/”并渲染直接link.to
值。
改变
to={`/${props.link.to}`}
至
to={props.link.to}
演示
推荐阅读
- java - 如何将 ChangeHistory 添加到我的所有实体
- json - 如何从嵌套字典(多级)创建 MultiIndex 数据框
- mongodb - 我的 mongodb 是存储刷新令牌的正确位置吗?
- javascript - GCP:Stripe webhook 错误:未找到与有效负载的预期签名匹配的签名
- gitlab - Gitlab 与 Hashicorp Vault 的集成
- .net-core - Ocelot Gateway Aggregation:当每个 API 有不同的 Query String 参数时
- reactjs - React 应用程序、.NET Core 3.1 API 和对 Microsoft Graph 的调用的配置
- javascript - 有没有办法从一开始就制作动画 gif 播放?
- python - 使用布局切片时,Django 脆皮表单“提供给 {%crispy %} 标签的帮助对象必须是一个crispy.helper.FormHelper 对象”
- python - 为什么不应该在 Django 的生产级使用 MEDIA_ROOT 和 MEDIA_URL?