首页 > 解决方案 > React Router v4 URL with params error when / at end

问题描述

我对 React 路由器有疑问。

我在代码沙箱中创建了一个简单的应用程序来演示它。

链接到代码框

描述

当在路由器的末尾有一个“/”或“/param”时,点击其他链接后,它会添加额外的单词。

例如有 4 个菜单项

何时 url https://foo.com/forecast添加一个“/”或一些参数“/2”,然后单击除 Cash In Performance url 之外的其他菜单项后将如下所示(例如单击 Monitor)

https://foo.com/forecast/newmonitor

但应该是https://foo.com/newmonitor

重现步骤

  1. 转到沙箱上的代码(使用上面的链接)

  2. 点击“预测中的现金”链接

    网址应该是这个https://myjn2170zp.codesandbox.io/forecast

  3. 然后单击三个预测之一。

    例如 Forecast 1 和 url 应该是这个 https://myjn2170zp.codesandbox.io/forecast/1

  4. 之后点击监控链接

    网址是这样的https://myjn2170zp.codesandbox.io/forecast/newmonitor

    但应该是这样的https://myjn2170zp.codesandbox.io/newmonitor

网址中添加了“预测”一词,但不应该是这样的。

标签: reactjsreact-router

解决方案


您需要将初始链接设置/为在开头。否则,像href="something"总是这样的链接会被解释为转到当前文件夹中的“某事”。这是正常的浏览器行为,与 react/react-router 无关。

所以使用

const menuItems = [
  {
    key: 1,
    name: "Cash In Performance",
    icon: "itm_icon-insert_chart",
    link: "/"
  },
  {
    key: 2,
    name: "Cash in Forecast",
    icon: "itm_icon-turnover",
    link: "/forecast"
  },
  {
    key: 3,
    name: "Cash In List",
    icon: "itm_icon_list",
    link: "/cashinlist"
  },
  {
    key: 4,
    name: "Monitor",
    icon: "itm_icon-dvr",
    link: "/newmonitor"
  }
];

编辑测试反应路由器


推荐阅读