与打字稿一起使用时的React Router问题

时间:2020-05-25 16:44:10

标签: typescript react-router

我正在使用打字稿和react-router(5.2.0)

我有一个需要匹配参数(id)的组件

import React, { useEffect, useState } from 'react'
import { RouteComponentProps } from 'react-router-dom'

import users from '../../data/users'

type ShowParams = { id: string }

function Show(props: RouteComponentProps<ShowParams>) {
    const id = props.match.params.id
   return <div>{id}</div>
}

export default Show

在对RouteComponentProps进行模板处理时可以正常工作,但这会导致路由声明出现问题 一旦在“显示”中正确定义了道具,路线声明就会在组件上显示错误

<Route path="/companies/:id" exact={true}  component={ShowCompany} />
  Overload 1 of 2, '(props: Readonly<RouteProps>): Route<RouteProps>', gave the following error.
    Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'ComponentClass<any, any> | FunctionComponent<any> | ComponentClass<RouteComponentProps<any, StaticContext, PoorMansUnknown>, any> | FunctionComponent<...> | undefined'.
 Type 'Element | undefined' is not assignable to type 'ReactElement<any, any> | null'.
          Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.
  Overload 2 of 2, '(props: RouteProps, context?: any): Route<RouteProps>', gave the following error.
    Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'ComponentClass<any, any> | FunctionComponent<any> | ComponentClass<RouteComponentProps<any, StaticContext, PoorMansUnknown>, any> | FunctionComponent<...> | undefined'.
      Type '(props: RouteComponentProps<ShowParams, StaticContext, PoorMansUnknown>) => Element | undefined' is not assignable to type 'FunctionComponent<any>'.  TS2769

这是非常合理的,因为它不再能够在没有props声明的情况下仅渲染组件

如何在路线中声明道具类型。

0 个答案:

没有答案