React中解构useParams为何可使用任意属性名?与普通对象解构差异解析
useParams() in React Router? Great question — this is a common point of confusion, but the short answer is: it doesn’t break object destructuring rules at all. Let’s unpack why this feels different from regular object destructuring.
First, let’s recap how standard object destructuring works, using your example:
const person = { name: "jon", age: 32, location: "UK" }; const { name } = person; // Works because "name" exists on the object const { abc } = person; // Returns undefined because "abc" isn’t a property of person
This makes sense: you can only destructure properties that actually exist on the object.
Now, let’s talk about useParams(). The key thing to understand is what this function returns:
useParams()gives you an object where the property names match the URL parameters you defined in your route configuration.
For example:
- If your route is
<Route path="/products/:productId" element={<ProductPage />} />, then when you visit/products/123,useParams()will return{ productId: "123" }. - If you change the route to
<Route path="/products/:randomName" element={<ProductPage />} />, thenuseParams()will return{ randomName: "123" }instead.
So when you write const { randomName } = useParams(), you’re not "breaking" rules — you’re just destructuring a property that does exist on the object returned by useParams(), because you defined that parameter name in your route.
If you tried to destructure a name that doesn’t match any URL parameter in your route, you’d still get undefined, just like with regular objects:
// Route is /products/:productId const { randomName } = useParams(); // randomName will be undefined!
To put it simply:
- Regular object destructuring relies on static, pre-defined properties.
useParams()returns an object with dynamic properties that are determined by your route’s URL parameters. As long as you use a name that matches one of those parameters, it works — just like any other object destructuring.
内容的提问来源于stack exchange,提问作者Viking

