0
Follow
0
View

React router v6 easiest way to access params outside route

liuguoyuch1406 注册会员
2023-01-24 20:46

react-router v6: The most easiest way to get an id from url. Caution(This only works if your component is a child of a componentThis only works if your component is a child of a component)

import { useParams } from "react-router-dom";
const { id } = useParams();

return(
    <>
        

This is useParams id = {id}

);
jmshxy5233 注册会员
2023-01-24 20:46

You can use matchPath:

react-router v6:

const match = matchPath({ path: "/users/:id" }, "/users/123");

react-router v5:

const match = matchPath("/users/123", {
  path: "/users/:id",
  exact: true,
  strict: false
});
qq328170374 注册会员
2023-01-24 20:46

The id route match param is only available on the params object of all ancestor and descendent Route components within a Routes component.

If the Menu component is capable of using the useParams hook (and there's a way to inject params as a prop if Menu is a class component) there is a refactor you can do where Menu is rendered as part of a layout along with an Outlet component and it will then be in the route hierarchy to access the route params.



   // <-- descendent route match params accessible here
         // <-- nested routes rendered here
      
    }
  >
    } />
    Id" element={} />
  

Example Menu component:

const Menu = () => {
  const params = useParams();
  console.log("Menu", params);
  return ...;
};

About the Author

Question Info

Publish Time
2023-01-24 20:46
Update Time
2023-01-24 20:46

Related Question

在React中将函数传递给无状态函数组件时遇到问题

如何使下拉在ReactJs从查询和获取值

React中未定义的道具的useState

Reactnative获取数据并将其保存为asyncstorage

如何用console.log测试react工具包查询

反应路由器v6 -如何使用@符号在路由?

我应该如何结合react-i18next与从数据库中获取的内容?

我如何通过一个字典从python到react作为一个对象?(复制)

JS对象更新+ React减速器

为什么我的React应用程序不显示React功能?