简体   繁体   English

如何有效地使用 react-router Link?

[英]How can i use react-router Link efficiently?

when I use the Link in the navbar in react it takes me to the suggested URL again and again even if I am present at that home,how can I redirect conditionally such that if I am on the home page then after clicking the home button again, I will not go to the home page again当我使用导航栏中的链接进行反应时,即使我在那个家中,它也会一次又一次地带我到建议的 URL,我如何有条件地重定向,如果我在主页上,然后再次单击主页按钮,我不会再go到首页了

<Link className="link" to="/leaderboards">
      <Home/>
</Link>

Use <NavLink /> component to redirect to other routes and set the active className as disabled class.使用<NavLink />组件重定向到其他路由并将活动 className 设置为禁用 class。

App应用程序

  <NavLink to="/" className="link" activeClassName="disabled-link">Home</NavLink>

CSS CSS

.disabled-link {
  pointer-events: none;
}

That's not how you use a Link .这不是您使用Link的方式。 You just specify a pathname in a Link component, and manage your paths-components inside a Router .您只需在Link组件中指定路径名,并在Router中管理路径组件。

Now you just render a <Home /> component always, hence the issue.现在您只需要始终渲染一个<Home />组件,这就是问题所在。

The open Github issue (at time of writing) for this is here: https://github.com/ReactTraining/react-router/issues/5362开放的 Github 问题(在撰写本文时)在这里: https://github.com/ReactTraining/react-router/issues/5362

To reiterate the solution here , you can create a hook for to prevent similar locations from being pushed consecutively:这里重申解决方案,您可以创建一个钩子来防止连续推送类似的位置:

import { useHistory } from "react-router-dom";

export default function useLocationBlocker() {
  const history = useHistory();
  useEffect(
    () => {
      history.block(
        (location, action) =>
          action !== "PUSH" ||
          getLocationId(location) !== getLocationId(history.location)
      );
    },
    [] // eslint-disable-line react-hooks/exhaustive-deps
  );
}

function getLocationId({ pathname, search, hash }) {
  return pathname + (search ? "?" + search : "") + (hash ? "#" + hash : "");
}

To reproduce, click the Home link more than once and notice that you can press the back button the same number of times.要重现,请多次单击主页链接,并注意您可以按相同次数的后退按钮。 ( https://codesandbox.io/s/r0wXp0Njw?file=/index.js ) https://codesandbox.io/s/r0wXp0Njw?file=/index.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM