client-api
客户端使用的api, 需要在顶层加上use client
- 指定了
use client表示使用客户端渲染
什么时候使用客户端组件
- 添加交互性和事件侦听器
- 使用状态和生命周期
- 浏览器的API
useParams
useParams 是一个客户端组件的hook,可以让你读取由当前 URL 路由的query参数。
'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 <></>
}
usePathname
usePathname 是一个客户端组件的hook,可用于读取当前 URL 的路径。
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
useRouter
useRouter是客户端的 路由hooks,提供了路由的操作
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<button
type="button"
onClick={() => router.push('/dashboard', { scroll: false })}
>
Dashboard
</button>
)
}