【问题标题】:How to specify the result type of useParams with react router v6?如何使用反应路由器 v6 指定 useParams 的结果类型?
【发布时间】:2021-11-16 16:45:28
【问题描述】:

在 react router v5 中,为了指定 useParams 的结果类型,我使用了:

const { param1, param2 } = useParams<{ param1: string, param2: string }>();

如何使用 react router v6 做到这一点?

我不知道如何输入多个参数(例如:useParams&lt;"param1"&gt;()),我不知道如何将参数输入为string 而不是string | undefined(请参阅question)。

【问题讨论】:

    标签: typescript react-router-dom


    【解决方案1】:

    我正在寻找同样的东西,在查看 useParams 的类型后,我发现您需要将 params 的键作为字符串传递,例如:

    const { param1 } = useParams<'param1'>();
    

    如果您想要多个参数,只需使用 typescript 的 |,如下例所示。

    type Params = 'a' | 'b' | 'c';
    // ...
    const params = useParams<Params>();
    

    由于反应路由器类型,返回的对象的值将始终具有 string | undefined 类型。

    export declare type Params<Key extends string = string> = {
        readonly [key in Key]: string | undefined;
    };
    

    但归根结底,您始终可以使用 typescript 的 as

    interface Params {
        a: string;
    }
    
    const params = useParams<keyof Params>() as Params;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 2021-10-17
      • 2020-10-04
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      相关资源
      最近更新 更多