You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router@v6的useParams钩子泛型要求传入string是否正常?

enter image description here

react-router v6 内置类型定义对 useParams 泛型做了更严格的约束,要求泛型传入的对象所有属性值必须为 string | undefined,这是因为URL路径参数原生都是字符串类型,该设计比旧版 @types/react-router 的泛型规则更严谨。

可用解决方案

方案1:标准用法(推荐)

直接按照约束定义泛型,拿到参数后如果需要其他类型再手动转换:

// 示例路由路径:/goods/:goodsId/:category
const { goodsId, category } = useParams<{
  goodsId: string
  category: string
}>();

// 需要数字类型参数可自行转换
const numericGoodsId = Number(goodsId);

方案2:类型断言兼容旧写法(不推荐,会丢失类型安全校验)

如果要直接复用旧的自定义对象类型,可以用类型断言绕开约束:

interface CustomParams {
  goodsId: number
  category: string
}
const params = useParams() as unknown as CustomParams;

方案3:类型化路由自动推断(v6.4+ 推荐)

如果使用 createBrowserRouter 等数据路由API定义路由,useParams 可以自动推断参数类型,无需手动传入泛型:

// 路由定义示例
const router = createBrowserRouter([
  {
    path: '/user/:userId',
    element: <UserPage />
  }
])

// UserPage 组件内直接使用,userId 会被自动推断为 string | undefined
const { userId } = useParams();

内容的提问来源于stack exchange,提问作者Eugene Mormul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:27:04