如何在反应中使用钩子路由器获取当前 url 路径?

How to get the current url path using hook router in react?

我是 React 和 React Hooks 的新手。我正在使用 hookrouter 包,我试图用谷歌搜索这个问题,但没有找到太多相关信息。

我想要什么?

我正在尝试获取当前 url 路径。例如对于 https://example.com/users/temp,我想获得 /users/temp

如有任何帮助,我们将不胜感激。提前致谢!

我终于在 github doc 上找到了。

import {usePath} from 'hookrouter';

const PathLabel = () => {
    const path = usePath();
    return <span>Your current location: {path}</span>;
}

我想让你知道还有一种通用方法 return 使用 Javascript 的路径,以防你没有在不同的项目上使用 hookrouter

只需调用 window.location.pathname

我正在使用它根据客户端使用三元表达式在哪条路线上为我的 Nav 组件中的链接设置活动类名。示例:

const NavList = props => {
    return (
        <NavContainer>
            <ul>
                {routes.map(({ key, href, label }) => (
                    <A href={href} key={key} className='route-link'>
                        <li
                            className={href === window.location.pathname ? 'active' : null}
                        >
                            {label}
                        </li>
                    </A>
                ))}
            </ul>
        </NavContainer>
    );
};