为什么 React router v6 useParams 返回属性可能为“未定义”的对象?
在下面的代码中,我的 IDE 指示
const slug: string | undefined
。
const { slug } = useParams<"slug">();
Params
类型定义:
/**
* 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
参数的情况?
我认为这是一个有问题的设计选择。 React Router 6 不支持可选参数,所以没有明显的原因,但即使支持,用户也应该负责确定哪些参数是可选的。
解决这个问题的一种方法是:
export type MyParams = {
a: string;
b: string;
c: string;
};
const { a, b, c } = useParams<keyof MyParams>() as MyParams;
如果路径没有定义参数,则路由参数可能是未定义的。
示例:“/路径/到/页面”
没有可访问的路由匹配参数。
如果您尝试访问参数
const { id } = useParams();
那么
id
当然是未定义的。
一种解决方法是扩展模块并更改所需的类型。
创建
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 };
}
就我而言,我只是希望通过 React 路由器路径传入
id
:
<Route path="/person/:id" element={<UpdatePerson />} />
我想不出一句台词,所以最终决定:
let { id } = useParams();
id = id as string;