简体   繁体   English

如何使用 react-dom-router 处理活动路由/路由更改

[英]How to handle active route/route change with react-dom-router

I have an App top-level component, that has a menu and routes.我有一个App顶级组件,它有一个菜单和路线。 On menu click I update the active item to reflect the selected route.在菜单上单击我更新活动项目以反映所选路线。 Here's the code:这是代码:

const [activeItem, setActiveItem] = useState(window.location.pathname === '/' ? 'home' : getRouteName());
...
const handleItemClick = (e, { name }) => {
  setActiveItem(name);
  window.document.title = 'MyApp - ' + name.charAt(0).toUpperCase() + name.slice(1);
};

const MenuItem = ({name, title, link}) => (
  <Menu.Item
    as={Link}
    to={link}
    name={name}
    title={title}
    active={activeItem === name}
    onClick={handleItemClick}
  >
    {title}
  </Menu.Item>
);
...
<Menu /> //iterate over items
<Switch>
  <Route exact path="/" component={Home} />
  ...
</Switch>

And it works well, UNTIL one of the components redirects to another component.它运行良好,直到其中一个组件重定向到另一个组件。 So if I go to /comp1 (whether by clicking or directly browsing) the activeItem will be comp1 and the comp1 menu item will look active.因此,如果我将 go 转到/comp1 (无论是通过单击还是直接浏览), activeItem将是comp1 ,并且comp1菜单项将看起来处于活动状态。 But if I go to comp2 and add a button to navigate to comp1 (either using a <Link> component, or history.push('/comp1') , the active item remians on comp2 .但是,如果我 go 到comp2并添加一个按钮以导航到comp1 (使用<Link>组件或history.push('/comp1') ,则活动项目 remians on comp2

Any ideas how to trigger a change in the App compoinent to reflect a route change, preferably without needing to put the handleActiveItem function into context, or pass it along to all other components?任何想法如何触发App组件的更改以反映路由更改,最好不需要将handleActiveItem function 放入上下文,或将其传递给所有其他组件?

You can use NavLink to achieve the same result and it's a bit simpler as the active item is handled for you.您可以使用 NavLink 获得相同的结果,并且它会更简单一些,因为活动项目已为您处理。

https://reactrouter.com/web/api/NavLink https://reactrouter.com/web/api/NavLink

<NavLink> A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL <NavLink> A special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL

<NavLink to="/foo">foo</NavLink>
<NavLink to="/bar">bar</NavLink>

Found a solution!找到了解决办法!

I'm now using the useLocation hook provided by react-router-dom to trigger an effect that changes the active item and the page title.我现在正在使用react-router-dom提供的useLocation挂钩来触发更改活动项目和页面标题的效果。 It gets fired every time the location changes, regardless if by the user or an inner component.每次位置更改时都会触发它,无论是用户还是内部组件。

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

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