相关疑难解决方法(0)

为什么 React router v6 useParams 返回属性可能为“未定义”的对象?

为什么 React router v6 useParams返回属性可能为“未定义”的对象?

在下面的代码中,我的 IDE 指示const slug: string | undefined.

const { slug } = useParams<"slug">();
Run Code Online (Sandbox Code Playgroud)

这是因为Params类型定义

/**
 * The parameters that were parsed from the URL path.
 */
export type Params<Key extends string = string> = {
  readonly [key in Key]: string | undefined;
};
Run Code Online (Sandbox Code Playgroud)

但为什么不Params这样定义(没有| undefined):

export type Params<Key extends string = string> = {
  readonly [key in Key]: string;
};
Run Code Online (Sandbox Code Playgroud)

如果带有参数的路由与 URL 匹配,则该参数不能为undefined。那么,有没有 …

typescript react-router-dom

21
推荐指数
3
解决办法
2万
查看次数

标签 统计

react-router-dom ×1

typescript ×1