首页 > 解决方案 > 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但我不确定如何实施解决方案以及我们的问题是否相同。非常感谢您的帮助!

标签: javascriptreactjsreact-router

解决方案


React Router 将以斜杠开头的路径视为绝对路径。在这里,您的数组中的url属性sections被视为相对路径,因为它们不以斜杠开头。

只需在数组中每个路径的开头添加一个斜杠:

const sections= [
    { title: 'All Categories', url: '/categories/all' },
    { title: 'Following', url: "/categories/following"},
]

推荐阅读