为什么 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
。那么,有没有 …