使用反应路由器,即使它们在那里也不能提取参数(使用打字稿)

时间:2018-01-17 21:52:04

标签: typescript react-router

我试图切换旧项目以使用react和react-router。我也是用于项目的打字稿的新手,所以任何解释都将不胜感激。

该路线的定义如下:

<Route
   path="/deployments/:somePrefix/:someId"
   component={SomeDetailPage}/>

但是,在SomeDetailPage中,当我尝试访问参数以便我可以调用它们上的函数((this.props.match.params.somePrefixthis.proper.match.params.someId))时,我收到此错误:

ERROR in [at-loader] src/public/components/some-detail-page.tsx:25:97
    Property 'somePrefix' does not exist on type '{}'

ERROR in [at-loader] src/public/components/some-detail-page.tsx:25:97
    Property 'someId' does not exist on type '{}'

然而,我知道那些参数存在,因为当我尝试测试并将参数作为div的一部分(只是随机测试)时,div不会加载并且我收到此错误:

Objects are not valid as a React child (found: object with keys {somePrefix, someId})

1 个答案:

答案 0 :(得分:2)

您如何为SomeDetailPage键入道具?

您需要确保从RouteComponentProps正确添加react-router-dom

例如,你需要的东西是

import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';

// Define what your match should look like
interface SomeDetailPageMatch {
    somePrefix: string;
    someId: string;
}

interface SomeDetailPagePropsFromParent {
    // Your custom props here
}

type SomeDetailPageProps = SomeDetailPagePropsFromParent &
    RouteComponentProps<SomeDetailPageMatch>; // Provide your match as generic

class SomeDetailPage extends React.Component<SomeDetailPageProps> {

...

然后它应该理解this.props.match.params.someIdthis.props.match.params.somePrefix存在。