为什么REACT路由器V6 useParams返回可能具有未定义属性的对象? [英] Why react router v6 useParams returns object with properties possibly 'undefined'?

查看:14
本文介绍了为什么REACT路由器V6 useParams返回可能具有未定义属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Reaction路由器v6useParams返回属性可能为‘unfined’的对象?

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

const { slug } = useParams<"slug">();

是因为Params type definition

/**
 * 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆