繁体   English   中英

如何使用反应路由器 v6 获取当前 URL 的最后一部分?

[英]How to get the last part of the current URL with react router v6?

如何使用反应路由器 v6 获得当前 url 的最后一部分?

例如:

如果当前路径是https://localhost:4200/example/example-details ,那么我想这样检查

const location = useLocation();

if (location.pathname === '/example-details')) {
  // do some stuff here
}

..但这总是返回完整路径。

它适用于location.pathname.includes('/example-details') ,但我很好奇是否有反应路由器的方法,就像 Angular 路由器一样。

检查

location.pathname.includes('/example-details')
const location = useLocation();
const [pathName, setPathName] = useState(null) ;

useEffect(() => {
    if(location) {
        let tmp = location.pathName.slice(location.pathName.lastIndexOf("/") , location.pathName.length) ;
        setPathName(tmp) ;
    }
}, [location])
const match = useMatch('/example/:lastPart')
const value = match?.props.lastPart;
if (!!value) {
    // do some stuff here
}

使用 useMatch,您可以将模板应用于当前位置,并在返回的 object 中提取一些部分作为道具。

暂无
暂无

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

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