本页还没有译文
本页 21 段还没译成Español,下面显示的是英文原文。useParams
还没翻译译自英文(reactrouter.com)本页 21 段都还没译
useParams
Framework Data Declarative
Summary
Returns an object of key/value-pairs of the dynamic params from the current URL that were matched by the routes. Child routes inherit all params from their parent routes.
Assuming a route pattern like /posts/:postId is matched by /posts/123
then params.postId will be "123".
import { useParams } from "react-router";
function SomeComponent() {
let params = useParams();
params.postId;
}Signature
function useParams<
ParamsOrKey extends string | Record<string, string | undefined> = string,
>(): Readonly<
[ParamsOrKey] extends [string] ? Params<ParamsOrKey> : Partial<ParamsOrKey>
>Returns
An object containing the dynamic route parameters
Examples
Basic Usage
import { useParams } from "react-router";
// given a route like:
<Route path="/posts/:postId" element={<Post />} />;
// or a data route like:
createBrowserRouter([
{
path: "/posts/:postId",
component: Post,
},
]);
// or in routes.ts
route("/posts/:postId", "routes/post.tsx");Access the params in a component:
import { useParams } from "react-router";
export default function Post() {
let params = useParams();
return <h1>Post: {params.postId}</h1>;
}Multiple Params
Patterns can have multiple params:
"/posts/:postId/comments/:commentId";All will be available in the params object:
import { useParams } from "react-router";
export default function Post() {
let params = useParams();
return (
<h1>
Post: {params.postId}, Comment: {params.commentId}
</h1>
);
}Catchall Params
Catchall params are defined with *:
"/files/*";The matched value will be available in the params object as follows:
import { useParams } from "react-router";
export default function File() {
let params = useParams();
let catchall = params["*"];
// ...
}You can destructure the catchall param:
export default function File() {
let { "*": catchall } = useParams();
console.log(catchall);
}AI 翻译查看英文原文