React中如何匹配路径与字符串?提取URL指定片段的其他方法
React路径提取一级目录的几种方法
利用useLocation的pathname配合split分割
不需要正则,直接通过split('/')把路径拆分成数组,取第二个元素即可。useLocation返回的pathname是当前路径的相对部分(比如/Test/marks),分割后数组为['', 'Test', 'marks'],索引1对应的就是你要的字符串。import { useLocation } from 'react-router-dom'; function YourComponent() { const { pathname } = useLocation(); const targetSegment = pathname.split('/')[1]; // 结果为'Test' // 这里写和数组匹配获取关联对象的逻辑 return <div>{targetSegment}</div>; }通过React Router的useParams(推荐路由配置明确时使用)
如果你的路由规则是预先定义的,比如设置为/:module/marks,可以直接用useParams获取对应参数值,这比手动分割更可靠。import { useParams } from 'react-router-dom'; // 假设路由配置为 <Route path="/:module/marks" element={<YourComponent />} /> function YourComponent() { const { module } = useParams(); // 这里module的值就是'Test' // 后续匹配逻辑 return <div>{module}</div>; }使用原生URL对象处理
直接借助浏览器原生的URL API解析完整地址,再处理路径部分,适合需要操作完整URL的场景:function YourComponent() { const currentUrl = new URL(window.location.href); const targetSegment = currentUrl.pathname.split('/')[1]; // 得到'Test' // 匹配逻辑 return <div>{targetSegment}</div>; }
内容的提问来源于stack exchange,提问作者ganesh kaspate
相关产品推荐
相关产品推荐

