【问题标题】:Why react router v6 useParams returns object with properties possibly 'undefined'?为什么反应路由器 v6 useParams 返回属性可能为“未定义”的对象?
【发布时间】:2021-12-27 17:18:15
【问题描述】:

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

在下面的代码中,我的 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 参数?

【问题讨论】:

    标签: typescript react-router-dom


    【解决方案1】:

    如果路径没有定义的参数,路由参数可能是未定义的。

    示例:“/path/to/page”

    没有可访问的路由匹配参数。

    如果您要尝试访问参数

    const { id } = useParams();
    

    那么id当然是未定义的。

    【讨论】:

      【解决方案2】:

      我认为这是一个值得商榷的设计选择。 React Router 6 doesn't support optional parameters,所以没有明显的原因,但即使支持,用户也应该负责确定哪些参数是可选的。

      绕过它的一种方法是:

      export type MyParams = {
        a: string;
        b: string;
        c: string;
      };
      
      const { a, b, c } = useParams<keyof MyParams>() as MyParams;
      

      【讨论】:

      • 您的链接丢失
      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 2021-11-10
      • 2022-12-16
      • 2020-01-05
      • 1970-01-01
      • 2015-11-27
      • 2020-04-14
      相关资源
      最近更新 更多