为什么REACT路由器V6 useParams返回可能具有未定义属性的对象? [英] Why react router v6 useParams returns object with properties possibly 'undefined'?
本文介绍了为什么REACT路由器V6 useParams返回可能具有未定义属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么Reaction路由器v6useParams返回属性可能为‘unfined’的对象?
在下面的代码中,我的IDE指示const slug: string | undefined
。
const { slug } = useParams<"slug">();
/**
* The parameters that were parsed from the URL path.
*/
export type Params<Key extends string = string> = {
readonly [key in Key]: string | undefined;
};
但为什么Params
不是这样定义的(没有| undefined
):
export type Params<Key extends string = string> = {
readonly [key in Key]: string;
};
如果带有参数的路由与URL匹配,则参数不能为undefined
。那么,当useParams
返回一个undefined
参数时,会出现这种情况吗?
推荐答案
如果路径没有定义参数,则可能未定义路由参数。
示例:";/Path/to/page";
没有要访问的路由匹配参数。
如果您尝试访问参数
const { id } = useParams();
那么id
当然是未定义的。
这篇关于为什么REACT路由器V6 useParams返回可能具有未定义属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文