Skip to main content

useParams

useParams 是一个客户端组件钩子,可让你读取由当前 URL 填充的路由的 动态参数

¥useParams is a Client Component hook that lets you read a route's dynamic params filled in by the current URL.

'use client'

import { useParams } from 'next/navigation'

export default function ExampleClientComponent() {
const params = useParams<{ tag: string; item: string }>()

// Route -> /shop/[tag]/[item]
// URL -> /shop/shoes/nike-air-max-97
// `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
console.log(params)

return '...'
}
'use client'

import { useParams } from 'next/navigation'

export default function ExampleClientComponent() {
const params = useParams()

// Route -> /shop/[tag]/[item]
// URL -> /shop/shoes/nike-air-max-97
// `params` -> { tag: 'shoes', item: 'nike-air-max-97' }
console.log(params)

return '...'
}

参数

¥Parameters

const params = useParams()

useParams 不带任何参数。

¥useParams does not take any parameters.

返回

¥Returns

useParams 返回一个对象,其中包含 动态参数 中填充的当前路由。

¥useParams returns an object containing the current route's filled in dynamic parameters.

  • 对象中的每个属性都是一个活动的动态段。

    ¥Each property in the object is an active dynamic segment.

  • 属性名称是段的名称,属性值是段所填充的内容。

    ¥The properties name is the segment's name, and the properties value is what the segment is filled in with.

  • 属性值将是 stringstring 的数组,具体取决于 动态段类型

    ¥The properties value will either be a string or array of string's depending on the type of dynamic segment.

  • 如果路由不包含动态参数,则 useParams 返回空对象。

    ¥If the route contains no dynamic parameters, useParams returns an empty object.

  • 如果在 Pages Router 中使用,useParams 将在初始渲染时返回 null,并在路由准备就绪后按照上述规则更新属性。

    ¥If used in Pages Router, useParams will return null on the initial render and updates with properties following the rules above once the router is ready.

例如:

¥For example:

路由URLuseParams()
app/shop/page.js/shop{}
app/shop/[slug]/page.js/shop/1{ slug: '1' }
app/shop/[tag]/[item]/page.js/shop/1/2{ tag: '1', item: '2' }
app/shop/[...slug]/page.js/shop/1/2{ slug: ['1', '2'] }

版本历史

¥Version History

版本变化
v13.3.0useParams 推出。