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

sol*_*liz 21 typescript react-router-dom

为什么 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。那么,有没有useParamsundefined参数返回的情况呢?

And*_*ena 34

我认为这是一个值得怀疑的设计选择。React Router 6 不支持可选参数,所以没有明显的原因,但即使它支持,用户也应该有责任确定哪些参数是可选的。

解决这个问题的一种方法是:

export type MyParams = {
  a: string;
  b: string;
  c: string;
};

const { a, b, c } = useParams<keyof MyParams>() as MyParams;
Run Code Online (Sandbox Code Playgroud)


Dre*_*ese 11

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

示例:“/路径/到/页面”

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

如果您尝试访问参数

const { id } = useParams();
Run Code Online (Sandbox Code Playgroud)

thenid当然是未定义的。


小智 5

一种解决方法是扩展模块并更改所需的类型。

创建src/react-router-dom.d.ts包含内容的文件:

import 'react-router-dom';

declare module 'react-router-dom' {
  export declare function useParams<
    ParamsOrKey extends string | Record<string, string | undefined> = string,
  >(): { [key in ParamsOrKey]: string };
}
Run Code Online (Sandbox Code Playgroud)