为什么要反应路由器 v6使用参数 https://reactrouter.com/docs/en/v6/api#useparams返回属性可能为“未定义”的对象?
在下面的代码中,我的 IDE 指示const slug: string | undefined
.
const { slug } = useParams<"slug">();
正是因为Params类型定义 https://github.com/remix-run/react-router/blob/c68df0c2328bcbd889ca486e790ba2efa3ea9ae4/packages/react-router/index.tsx#L735:
/**
* 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
param?
我认为这是一个值得怀疑的设计选择。React Router 6 不支持可选参数 https://github.com/remix-run/react-router/issues/7285,所以没有明显的原因,但即使它支持,用户也应该有责任确定哪些参数是可选的。
解决这个问题的一种方法是:
export type MyParams = {
a: string;
b: string;
c: string;
};
const { a, b, c } = useParams<keyof MyParams>() as MyParams;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)