javascript - React Router 导航 URL 附加到现有 URL
问题描述
我的 react-router-dom 有错误
我有一个使用以下内容渲染的组件:
<Route path='/categories/:url_type' component={Categories} exact />
基于 url 一个不同的参数,“following”或“all”,被传递到反应路由器,并在组件内部呈现不同的东西。
但是有一个错误:每当我想用第二个参数“如下”渲染我的组件时,如下所示:
http://localhost:3000/categories/following
,我之前访问的网站的网址没有被清除。所以如果我一直在“个人资料”网站上,我会得到这个
http://localhost:3000/profile/categories/following
结果,我得到一个错误并且没有呈现任何内容。
这是我在 html(Material UI)中访问它的链接:
const sections= [
{ title: 'All Categories', url: 'categories/all' },
{ title: 'Following', url: "categories/following"},
]
// I'm merging to arrays in my code, this is for simplicity
{sections.map((section)=>(
<Link component={RouterLink} to={section.url}>{section.link}</Link>
))}
这就是我处理链接的方式。函数“allCategories()”绝对有效:
useEffect(() => {
if (url_type === "all"){
allCategories("http://127.0.0.1:8000/api/category/")
}
else if (url_type === 'following'){
allCategories("http://127.0.0.1:8000/api/category/follow")
}
else {
history.push("/404")
}
}, []);
我已经看到这篇文章反应路由器堆叠 url但我不确定如何实施解决方案以及我们的问题是否相同。非常感谢您的帮助!
解决方案
React Router 将以斜杠开头的路径视为绝对路径。在这里,您的数组中的url
属性sections
被视为相对路径,因为它们不以斜杠开头。
只需在数组中每个路径的开头添加一个斜杠:
const sections= [
{ title: 'All Categories', url: '/categories/all' },
{ title: 'Following', url: "/categories/following"},
]
推荐阅读
- c++ - 将新的 char * 从 1 作为参数给出,元素介于 2 个索引之间
- python-3.x - 如何将嵌套字典转换为具有多索引的熊猫数据框?
- r - 确定此图的距离函数参数的合适值
- excel - VBA VLookup 来自另一个关于单元格更改的 VBA 工作表
- c# - 使用 NUnit 对隐式运算符进行单元测试
- excel - 将目标线添加到数据透视图
- python-3.x - Python3:在win10上使用OpenCV模拟本地网络摄像头设备
- python - 网页抓取时如何搜索特定的Unicode字符串?
- java - 如何在给定的 html 元素中使用 xpath 进行搜索?
- macos - 终端看不到或找不到 dms 文件