【问题标题】:React router with Typescript (function class)使用 Typescript 反应路由器(函数类)
【发布时间】:2019-07-03 14:53:10
【问题描述】:

我正在尝试带有 react 的 Typescript(以前从未工作过)。我解决了一个问题,但我不确定这是否是正确的方法。

所以我的反应路线看起来像这样

<Route exact path='/show/:id' component={ShowIssues} />

我解决的组件看起来像这样

import React from "react";
import { RouteProps } from "react-router-dom";

interface RouteInfo extends RouteProps {
  params: {
    id: string;
  };
}

const ShowIssues = ({ match }: { match: RouteInfo }) => {
  const { params }: { params: { id: string } } = match;
  const { id }: { id: string } = params;

  return <div>time to show the issue {id}</div>;
};

export default ShowIssues;

本场比赛的道具解决了吗?令人惊讶的是,我几乎没有发现任何关于函数组件的信息(并且钩子即将到来,所以我想提出这个疑问是有道理的)。

我的另一个疑问是const { params }: { params: { id: string } } = match; 有没有办法可以重复使用RouteInfo,所以我不必输入两次?

谢谢!

【问题讨论】:

    标签: javascript reactjs typescript react-router


    【解决方案1】:

    const { params }: { params: { id: string } }const { id }: { id: string } 类型是多余的,因为如果 match 输入正确,它们将被推断出来。

    Route props 是具有match 属性RouteComponentProps 的特定类型的对象。它接受match.params 类型作为泛型参数。

    应该是:

    interface RouteInfo extends RouteProps {
        id: string;
    }
    
    const ShowIssues = ({ match }: RouteComponentProps<RouteInfo>) => {
      const { params } = match;
      const { id } = params;
    
      return <div>time to show the issue {id}</div>;
    };
    

    【讨论】:

    • 完美,这正是我想要的。我每次都无法正确输入。
    • 很高兴它有帮助。
    • 只是为了仔细检查并确保一切正常:RouteComponentProps 已经指向params,所以我只需要在我的类型中指定id: stringparams 的包装失败了,没有它看起来不错
    • 没错。请参阅github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… 了解其工作原理。为了清楚起见,我更新了答案。
    • 不是&lt;Route /&gt; 的RouteProps 属性吗?在这里扩展它们似乎是多余的,实际上给我带来了奇怪的 TS 错误。这很好用:interface RouteInfo { ... .
    猜你喜欢
    • 2021-12-02
    • 2020-09-20
    • 2021-05-20
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2017-06-14
    • 2018-06-11
    • 2020-10-02
    相关资源
    最近更新 更多