gpt4 book ai didi

javascript - 为什么 React Router NavLink prop exact (v5) vs. end (v6) 会导致 url 中带有斜杠的不同结果

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

在 React Router 版本 5 中,我有一个 NavLink看起来如下:

<NavLink
to="/notes"
exact={true}
className="border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
activeClassName="bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
>
Home
</NavLink>
它同时识别 localhost:3000/noteslocalhost:3000/notes/带有斜杠作为事件网址。
在 React Router 版本 6 中,我将其重构为以下内容:
<NavLink
to="/notes" end
className={(navData) =>
navData.isActive
? "bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
: "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
}
>
Home
</NavLink>
这仅识别 localhost:3000/notes作为事件网址。
v6 中是否有办法将带有斜杠的版本也识别为事件 url?

最佳答案

我认为你混淆了react-router-dom v5 exact prop 表示,或者更确切地说,您将 exact 之间的行为混为一谈。和 strict Prop 。
v5

  • exact : 当true ,只有在位置为 时才会应用事件类/样式完全匹配 .
  • strict : 当true ,在确定位置是否与当前 URL 匹配时,将考虑位置路径名上的尾部斜杠。见 <Route strict> 文档以获取更多信息。

  • 请注意,关于完全匹配的重点是我的。
    v6
    react-router-dom版本 6 所有路由/链接始终完全匹配。 end NavLink 的 Prop 与斜杠 "/" 有更多关系比它做路由匹配。

    If the end prop is used, it will ensure this component isn't matchedas "active" when its descendant paths are matched. For example, torender a link that is only active at the website root and not anyother URLs, you can use:

    <NavLink to="/" end>
    Home
    </NavLink>

    解决您的问题

    Why React Router NavLink prop exact (v5) vs. end (v6) lead todifferent result with trailing slash in url


    这是因为您将苹果与橙子进行比较。如果您想实现从 v5 到 v6 关于尾部斜杠 "/" 的相同链接行为然后省略 end支柱。
    <NavLink
    to="/notes"
    className={(navData) =>
    navData.isActive
    ? "bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
    : "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
    }
    >
    Home
    </NavLink>
    Edit why-react-router-navlink-prop-exact-v5-vs-end-v6-lead-to-different-result-w

    关于javascript - 为什么 React Router NavLink prop exact (v5) vs. end (v6) 会导致 url 中带有斜杠的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70550172/

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