javascript 如何使用react router v6获取当前URL的最后一部分?

zlwx9yxi  于 2023-05-16  发布在  Java
关注(0)|答案(4)|浏览(143)

如何使用react router 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')一起工作,但我很好奇是否有一种方法与react路由器一起使用,就像Angular路由器一样。

y3bcpkx1

y3bcpkx11#

const match = useMatch('/example/:lastPart')
const value = match?.props.lastPart;
if (!!value) {
    // do some stuff here
}

使用useMatch,您可以将模板应用到当前位置,并提取一些部分作为返回对象中的 prop 。

3htmauhk

3htmauhk2#

检查

location.pathname.includes('/example-details')
tvmytwxo

tvmytwxo3#

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])
nr9pn0ug

nr9pn0ug4#

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

function MyComponent() {
  const match = useMatch("/:firstRoute/:secondRoute/*");
  const { firstRoute, secondRoute } = match.params;
  const lastRoute = match.params["*"];

  return (
    <div>
      <p>First route: {firstRoute}</p>
      <p>Second route: {secondRoute}</p>
      <p>Last route: {lastRoute}</p>
    </div>
  );
}

相关问题